sherry
sherry

Reputation: 1

Unwanted spaces added in print function call

Number of characters in yellow_Daisy : 12
Number of characters in 6yellow6 : 8

how can I move the : closer to the words. here is what I wrote but I don't know how to get read of the space

print('Number of characters in', password1,':', len(password1))
print('Number of characters in', password2,':', len(password2))

Upvotes: 0

Views: 72

Answers (3)

tdelaney
tdelaney

Reputation: 77337

f-strings to the rescue.

print(f'Number of characters in {password1}: {len(password1)}')
print(f'Number of characters in {password2}: {len(password2)}')

With f-strings (python 3.6 and later), you can put python expressions in curly braces. Now you have a single string with the spacing and formatting you want, and {..} will be replaced with the evaluation of the expression.

Upvotes: 3

Alex
Alex

Reputation: 846

I think tdelaney has provided a great answer. Another simpler way (but not so clear as f-strings) is to use concatenation (+) instead of commas, e.g.

print('Number of characters in' + password1 + ':' + str(len(password1)))

Upvotes: 0

michaelgbj
michaelgbj

Reputation: 294

try formatting the string as such:

print("Number of characters in {a}:{b}".format(a=password1, b=len(password1)))

or print(f"Number of characters in {password1}:{len(password1)}")

Upvotes: 0

Related Questions