2

Is it possible to print multiple strings on one line in such a way that the final string will always be x amount of space from the left? For example, is there anyway to print a result similar to this, where strZ is always printed in the same place (not right-justified)?

strA strB strC        strZ 
strA                  strZ 
strC StrB strD strE   strZ
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user2931070
  • 67
  • 2
  • 3

1 Answers1

5

Using str.format:

fmt = '{:<4} {:<4} {:<4} {:<6} {:<4}'
print(fmt.format('strA', 'strB', 'strC', '', 'strZ'))
print(fmt.format('strA', '', '', '', 'strZ'))
print(fmt.format('strA', 'strB', 'strC', 'strE', 'strZ'))

prints

strA strB strC        strZ
strA                  strZ
strA strB strC strE   strZ

See Format String Syntax.

falsetru
  • 357,413
  • 63
  • 732
  • 636