how to get rid of spaces between variables and strings when printed

Viewed 1397
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?

4 Answers

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, '.']))

You can use.

name = 'Alan'
print('My name is', name + '.')

or

name = 'Alan'
print('My name is '+ name + '.')

here comes the magic

name = 'Alan'
print('my name is '+name+'.')

There are two good ways to accomplish this. The best way is to use the optional argument to print, which is sep:

print('My name is', name, '.', sep='')

Another way is to use string concatenation. It's a little bit slower, but you can extend the concept to a lot of other areas. Concatenating strings joins them together without a space in between:

print('My name is' + name + '.')
Related