Python Forum

Full Version: Basic Python question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Simple question... embarrassed I am struggling with this.

I am printing a string variable but it shows a leading and trailing space. Here is a.piece of code:
a="mystring"
print("[",a,"]")
output of this shows: mystring "
" mystring "

why are there spaces before and after?
The output I get after running your code is:
Output:
[ mystring ]
It is because print function's default separator is a whitespace. If you want to change the separator, you can specify it explicitly:
print("[",a,"]", sep='')
An alternative you can use, which is also more generic, is to format the string (with format method):

print("[{}]".format(a))
Thank you. That makes sense.