Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a space between two string items in Python

Tags:

python

spaces

>>> item1="eggs"
>>> item2="sandwich"

>>> print(item1+item2)

>>> Output: eggssandwich

My main goal is to put a space between eggs and sandwich.

But i'm unsure on how to. Any help would be appreciated

like image 434
Henry Green Avatar asked Mar 01 '16 12:03

Henry Green


2 Answers

Use .join():

print(" ".join([item1, item2]))

The default for print, however, is to put a space between arguments, so you could also do:

print(item1, item2)

Another way would be to use string formatting:

print("{} {}".format(item1, item2))

Or the old way:

print("%s %s" % (item1, item2))
like image 163
zondo Avatar answered Sep 18 '22 14:09

zondo


Simply!

'{} {}'.format(item1, item2)  # the most prefereable

or

'%s %s' % (item1, item2)

or if it is just print

print(item1, item2)

for dynamic count of elements you can use join(like in another answer in the tread).

Also you can read how to make really flexible formatting using format language from the first variant in official documentation: https://docs.python.org/2/library/string.html#custom-string-formatting

Update: since f-strings were introduced in Python 3.6, it is also possible to use them:

f'{item1} {item2}'
like image 25
Andrey Rusanov Avatar answered Sep 19 '22 14:09

Andrey Rusanov