Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 621
Alan Aristizabal Avatar asked Dec 22 '18 01:12

Alan Aristizabal


People also ask

How do you print a variable without spaces between values?

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 '' .

How do you remove a space between string and variable in print statement in Python?

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.


1 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, '.']))
like image 157
Mad Physicist Avatar answered Oct 07 '22 22:10

Mad Physicist