0

I have a code that appends text into a text file but I need to do it in such a way that there is a separation of a specific number of spaces between the data entered. For example my program asks the user to input text 4 times so it would look like this:

enter name: Mike
enter middle name: Jason
enter last name: Bell
enter age: 24

Now the text file will contain the following:

MikeJasonBell24

However, I need it to be displayed such that first name has a 'limit' of 10 spaces, middle name 6 spaces, last name 5 space, age 2 spaces. So the text file will contain the following:

Mike      Jason Bell 24

Please let me know if there is any confusion in the question.

2 Answers2

0

You may use the options of the formatting, to specify the length to pad with spaces

name = "Mike"
middle_name = "Jason"
last_name = "Bell"
age = 24

result = f"{name:10s}{middle_name:6s}{last_name:5s}{age:2d}"
print(result)  # "Mike      Jason Bell 24"

But as you don't know the size of words, you be in trouble if one is longer that the size you allowed, because it'll be stuck to the next, one, you can fix that problem using a single space, between each, or a tabulation char

result = f"{name}\t{middle_name}\t{last_name}\t{age}"
print(result)  # "Mike    Jason   Bell    24"

And as you may need to retrieve the different part form the row, you could use split() without parameter

print(result.split())  # ['Mike', 'Jason', 'Bell', '24']
azro
  • 53,056
  • 7
  • 34
  • 70
0

try this:

#input data
first_name = "Mike"
middle_name = "Jason"
last_name = "Bell"
age = 24

result = '{:10s} {:6s}{:5s}{:2d}'.format(first_name, middle_name, last_name, age)
print(result)
with open("file.txt", 'w') as f:
    f.write(result)
    f.write("\n")

#Outpu data:

Mike       Jason Bell 24
ganaidu
  • 96
  • 1
  • 3