4

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?

  • 1
    use this for elif part `elif x >= 4: x = str(x)+'th' print(x)` – IrAM Dec 20 '20 at 07:03
  • From the [docs](https://docs.python.org/3/library/functions.html#print): *"`print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)` Print `objects` to the text stream `file`, __separated by `sep`__ and followed by `end`."* – Tomerikoo Dec 20 '20 at 12:32

5 Answers5

8

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))
greybeard
  • 2,249
  • 8
  • 30
  • 66
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
3

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

So change the last line from:

        print(x, 'th')

To:

        print(str(x) +'th')
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

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

robbo
  • 525
  • 3
  • 11
0

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")
ppwater
  • 2,315
  • 4
  • 15
  • 29
0

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

Irfan wani
  • 4,084
  • 2
  • 19
  • 34