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

Viewed 302

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?

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

Don't use , comma, that automatically gives a space.

So change the last line from:

        print(x, 'th')

To:

        print(str(x) +'th')

You can convert the number to a string and then print it as

print(str(x) + 'th')

Or you can change the value of the default separator to an empty string rather than the default space:

print(x, 'th', sep='')

Print function

You can convert the number to a string and then print it. print(str(x) + 'th')

Or just use sep

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', sep="")

Using format strings

Or you can just use this though.

print("{num}th".format(num=x))

Or f strings

print(f"{x}th")

Use fornatted string to plugin a variable in a string. f"{x}th"

Related