0

I have a tuple contains both string and float values (which are read from a txt file and calculated by me, respectively) and I want to write it to another txt file.

variables = (line.split()[0],line.split()[1], velocity) #velocity is a floating number, others are #string
output_file.write('%s  %s  %4.2f \n' % variables)

These lines are in a for loop. I want to align each variable in each line as right justified. How can I do that?

Please note that string items don't have same character in each line.

Celeo
  • 5,583
  • 8
  • 39
  • 41
wthimdh
  • 476
  • 1
  • 5
  • 19

1 Answers1

3

Python has several ways to format strings. In the form you use, you get right alignment by specifying a field length and optional padding. Python right aligns to fit the field length by default. Your float calculation already has a field length, so just decide on a length for the strings also. Its easy if you already have a max field size in mind. Here is an example of 10 spaces per string:

'%10s  %10s  %4.2f \n' % variables
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • the problem is the following: I used something like %5.2f for float. So it writes 99.48. But in the next line, number is 100.34. The following floats are not right aligned. I need the float variables to be right aligned :( How can I fix it? – wthimdh Sep 16 '14 at 22:25
  • 1
    @tgb, in 5.2, the 5 is the total size and the 2 is the number of digits past the decimal. Since 100.34 is already 6 chars, you've overrun your formatting size. Try something like %10.2f to see the difference. – tdelaney Sep 16 '14 at 22:39
  • thank you so much^^ last question is regarding the string formatting. the strings should be left-aligned while the floating numbers have to be right-aligned. Now I covered floats. But, any hint to align strings from right? – wthimdh Sep 16 '14 at 23:02
  • 1
    Add a dash to left align, like `%-10s %-10s %10.2f` – tdelaney Sep 16 '14 at 23:08
  • huge thanks for your great help ^^ – wthimdh Sep 16 '14 at 23:12