Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python add a whitespace after printing int then string? [duplicate]

Tags:

python

This is my code:

num = input('Amount of numbers:')
num = int(num)
for x in range(1, num + 1):
    if x == 1:
        print('1st')
    elif x == 2:
        print('2nd')
    elif x == 3:
        print('3rd')
    elif x >= 4:
        print(x, 'th')

This is the output(sample):

Amount of numbers:8
1st
2nd
3rd
4 th
5 th
6 th
7 th
8 th

As you can see, all numbers after 4 have a whitespace between it and 'th'. How do I fix this?

like image 721
Alex Ponomarev Avatar asked Oct 17 '25 10:10

Alex Ponomarev


1 Answers

you can optionally give a separator argument of whatever you want for "how comma should behave" (as another option to the other answers...

print("a","b",sep="+")
a+b

so you could just use ""

print("a","b",sep="")
ab

if you do decide to use a single string as the other answers suggest you should really just use string formatting instead of + concatenation

print("{num}th".format(num=x))
like image 115
Joran Beasley Avatar answered Oct 19 '25 23:10

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!