Python Forum
Basic Python question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Basic Python question (/thread-9015.html)



Basic Python question - vmenon - Mar-17-2018

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?


RE: Basic Python question - j.crater - Mar-17-2018

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))



RE: Basic Python question - vmenon - Mar-17-2018

Thank you. That makes sense.