name = 'Alan'
print('My name is', name, '.')
When these two lines are run, there is a space between 'Alan'
and the period. How do I get rid of the space between them?
To print multiple values or variables without the default single space character in between, use the print() function with the optional separator keyword argument sep and set it to the empty string '' .
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
You can set sep=''
but then explicitly mention the space before the name:
print('My name is ', name, '.', sep='')
A better way might be using string formatting:
print('My name is {}.'.format(name))
With python 3.6+, you can use f-strings for a more concise way of doing the same thing:
print(f'My name is {name}.')
Finally, the least flexible alternative is just concatenating the strings together:
print('My name is ' + name + '.')
You can even replicate what print
does internally when you set sep=''
:
print(''.join(['My name is ', name, '.']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With