[Tutor] Hello World in Python without space

Peter Otten __peter__ at web.de
Sun Jul 10 14:05:25 CEST 2011


Robert H wrote:

> I have Python 3.2 installed on Windows 7. I am a complete beginner playing
> around with the basic functions. My problem is the following script:
> 
> 
> name="world"
> print("Hello", name,"!")
> 
> 
> The result is:
> Hello world !
> 
> 
> However, I don't want the space before the exclamation mark. I want this:
> Hello world!
> 
> 
> I tried to solve the problem with e.g.:
> print("Hello",name.strip(),"!")
> but the result is the same.


print() by default inserts a space between its arguments. You can avoid that 
by specifying a separator explicitly with the "sep" keyword. Let me show it 
in the interactive interpreter which is generally a good place to experiment 
with small snippets of code:

>>> name = "Robert"
>>> print("Hello ", name, "!", sep="") # Note the explicit " " after "Hello"
Hello Robert!

Another goodie is that you can easily get useful information about modules, 
classes, keywords, and functions, e. g.

>>> help(print)

shows

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.

Use help() without argument to learn more about the interactive help.




More information about the Tutor mailing list