28

Probably an easy question that I couldn't quite find answer to before...

I'm formatting a table (in text) to look like this:

Timestamp: Word                        Number

The number of characters between the : after timestamp and the beginning of Number is to be 20, including those in the Word (so it stays aligned). Using python I've done this:

    offset = 20 - len(word)

    printer = timestamp + ' ' + word
    for i in range(0, offset):
        printer += ' '
    printer += score

Which works, but python throws an error at me that i is never used ('cause it's not). While it's not a huge deal, I'm just wondering if there's a better way to do so.

Edit:

Since I can't add an answer to this (as it's marked duplicate) the better way to replace this whole thing is

printer = timestamp + ' ' + word.ljust(20) + score
Mitch
  • 1,604
  • 4
  • 20
  • 36
  • I'm voting to re-open this question because it is asking about modifying a string, not printing it. Though there are answers that apply to both questions, the question itself is not the same. It's possible that there are answers that only apply to one of these two questions. – Aran-Fey Sep 15 '17 at 16:08
  • @Rawing I'd vote to keep it closed. Strings are immutable in python; you **can't** modify a string – Mitch Sep 16 '17 at 16:55

3 Answers3

61

You can multiply by strings by numbers to replicate them.

    printer += ' ' * offset
merlin2011
  • 71,677
  • 44
  • 195
  • 329
8

String formatting may work too

'{}: {: <20s}{}'.format("Timestamp", "Word", 200)
Timestamp: Word                200
iruvar
  • 22,736
  • 7
  • 53
  • 82
3

Try

printer += ' '*offset

instead of the for-loop

wastl
  • 2,643
  • 14
  • 27