Henry Green
Henry Green

Reputation: 243

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

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

Upvotes: 5

Views: 74991

Answers (6)

Shahab Rahnama
Shahab Rahnama

Reputation: 1012

There are a lot of ways ;) :

print(f'Hello {firstname} {lastname}')

Or

print("Hello", firstname, lastname)

Or

print("Hello", firstname + ' ' + lastname)

Or

print(' '.join(["Hello", firstname , lastname]))

Or

[print(i, end=' ') for i in ["Hello", firstname, lastname]]

Upvotes: 0

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

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

Upvotes: 10

NickBaldwin
NickBaldwin

Reputation: 1

Here are three easy solutions to add a space.

Add a space in between, but as noted above this only works if both items are strings.

print("eggs" + " " + "sandwich")

Another simple solution would be to add a space to end of eggs or beginning of sandwich.

print("eggs " + "sandwich")
print("eggs" + " sandwich")

These will all return the same result.

Upvotes: 0

Mide
Mide

Reputation: 1

# works every time
print(item1, item2)
# Only works if items 1 & 2 are strings.
print(item1 + " " + item2)

Upvotes: 0

cssko
cssko

Reputation: 3045

Just add the space!

print(item1 + ' ' + item2)

Upvotes: 2

zondo
zondo

Reputation: 20336

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

Upvotes: 20

Related Questions