0

I am trying to output a string from a tuple with different widths between each element.

Here is the code I am using at the moment:

b = tuple3[3] + ', ' + tuple3[4] + '          ' + tuple3[0] + ' ' 
+ tuple3[2] + '          ' + '£' + tuple3[1]

print(b)

Say for example I input these lines of text:

12345 1312 Teso Billy Jones
12344 30000 Test John M Smith

The output will be this:

Smith, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312

How can I keep the padding consistent with larger spacing between the 3 parts?

Also, when I input these strings straight from a text file this is the output I recieve:

  Smith
, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312

How can I resolve this?

Thanks alot.

3
  • Where is "Smith" in your input? All I see is "Senfkewjnrmith" Commented Dec 9, 2013 at 1:08
  • 1
    how about using tabs? \t Commented Dec 9, 2013 at 1:10
  • Thanks that sorted the spacing, but for some reason 'Smith' is still not in the same line as ', John M 12344 Test £30000' Commented Dec 9, 2013 at 1:13

1 Answer 1

5

String formatting to the rescue!

lines_of_text = [
    (12345, 1312,  'Teso', 'Billy',  'Jones'),
    (12344, 30000, 'Test', 'John M', 'Smith')
]

for mytuple in lines_of_text:
    name = '{}, {}'.format(mytuple[4], mytuple[3])
    value = '£' + str(mytuple[1])
    print('{name:<20} {id:>8} {test:<12} {value:>8}'.format(
        name=name, id=mytuple[0], test=mytuple[2], value=value)
    )

results in

Jones, Billy            12345 Teso           £1312
Smith, John M           12344 Test          £30000
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I have narrowed down the problem with the new line randomly starting and it's because I input the strings from a file with tuple(a.split(' ')) 'a' being the line inputed from the text file. However, with this method the tuple comes out in this format: ('12344', '30000', 'Test', 'Smith\n', 'John M'). How can I fix this?
Would you happen to know how the formatting can be done using variable padding? Like this: '{name:<var_padding} instead of {name:<20}, so the amount can be set with an argument?
@Mast: you can build the format-string first, ie fmt = "{{name:{width}}}".format(width=20) and then pass it to print, print(fmt.format(name="Billy")).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.