1

I want to print some text beside another text that has been printed before in python for example

print("Hello")
a="This is a test"
print(a)

What I mean is to print like this "HelloThis is a test" not in next line I know I shoud use print("Hello",a) but I wanted to use seprated print commands!!!!

hamidfzm
  • 4,595
  • 8
  • 48
  • 80

2 Answers2

5

Use end='' in the first print call:

print("Hello", end='')
a = "This is a test"
print(a)
#HelloThis is a test

Help on print:

print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • This only works in `Python-3.x` – dansalmo Oct 20 '13 at 16:58
  • @dansalmo There's a python-3.x tag on the question. – Ashwini Chaudhary Oct 20 '13 at 16:58
  • There is also a `Python` tag on the question. – dansalmo Oct 20 '13 at 17:46
  • 1
    @dansalmo: FWIW, the recommended policy is to use `Python` to specify the language and the version tag to specify which dialect you're using. So given the tags `python python-3.x`, the answers should typically be for 3. Sometimes the askers get this wrong, often because they don't guess that the difference is relevant, but if so the tags should be fixed instead. – DSM Oct 20 '13 at 21:57
  • @dansalmo This works on python 2.6 and python 2.7 if you add `from __future__ import print_function` at the top of the file. – SethMMorton Oct 20 '13 at 22:02
  • Many users searching for answers would not know this. 3.x answers would be better they included 2.x caveats such as those mention in these comments – dansalmo Oct 20 '13 at 22:11
-1

If you are using python 2.7 (python tag on question) you can place a comma after the print to not return a new line.

print("hello"),
print("world")

Will print "helloworld" all one one line. So in your case it will be:

print("Hello"),
print(a)

Or if your using python 3 (python3.x tag on question) use:

print("hello", end='')
print('world')

So in your case it will be:

print("Hello", end='')
print(a)
RMcG
  • 1,045
  • 7
  • 14