Temp14
Temp14

Reputation: 3

Random spacing when using /t in a string in Python 3.8.x

Second last line has the "problem".

This is the code:

cities = []
prompt = "Please enter the names of any five cities that you have visited."
prompt += "\nWe will compile them into a list for you"
num = 1
flag = True

while num <= 5 and flag:
    city = input(f"City {num}: ")
    if city.lower() == "quit":
        break
    else:
        cities.append(city)
        num += 1

print()

num = 0
place = ""
comp = ""
print("So you have visited the following cities:")
for place in cities:
    num += 1
    comp += f"{num}. {place}\t"
print(comp)

It is supposed to ask for 5 inputs and then number them and put them all in one sentence, as a string, then print that string.

It "works", there are no errors, but the space created in the result due to \t in the second last line always seems to vary. Sometimes there is no space at all, and sometimes there are two spaces. Same code, run over and over in command prompt, but different results every time in the behavior of \t.

It works perfectly if I replace the \t with four spaces.

What is the reason for this?

Upvotes: 0

Views: 1014

Answers (2)

Mike67
Mike67

Reputation: 11342

The tab just moves to the next tab stop. A tab does not equal four spaces. This is used to line up columns when printing multiple lines.

print("test\ttest")
print("test12\ttest")
print("test12345\ttest")

Output

test    test
test12  test
test12345       test

Upvotes: 2

Joe Ferndz
Joe Ferndz

Reputation: 8508

Do you want to try to change your format statement to be something like this.

for place in cities:
    num += 1
    comp += f"{num}. {place:15}" 
    #your string length will always be left justified to 15 chars 
print(comp)

Upvotes: 0

Related Questions