Jayden Klemas
Jayden Klemas

Reputation: 21

Escape characters barely work or are inconsistent (\t in particular)

I'm trying to make a program in Python 2.7. I'm trying to format a string so that it would look like this:

Spacing       Does       Not       Work

But I'm having a lot of trouble putting tabs between the words. Here's three ways that I have tried it, all of which have undesired results:

print "\t Spacing \t Does \t Not \t Work!"
print "        Spacing        Does        Not        Work!"
print "\t" + "Spacing" + "\t" + "Does" + "\t" + "Not" + "\t" + "Work!"

Which give the results of:

     Spacing     Does    Not     Work!
    Spacing        Does        Not        Work!
    Spacing Does    Not Work!

Now the middle one looks the best, but putting 8 spaces between words definitely isn't the best way to do this, right? Any help would be greatly appreciated, thanks!

Upvotes: 1

Views: 289

Answers (1)

cdarke
cdarke

Reputation: 44394

The size of a tab is not defined, and varies across platforms and even terminal systems on the same platform. So your first two lines are doomed to fail.

You don't use the tabs consistently anyway, because you mix them with spaces. You compare:

"\t" + "Spacing" + "\t" ->   "\tSpacing\t"

with:

"\t Spacing \t

Better to use format strings, for example to get three 12 character fields:

print "{:12}{:12}{:12}".format("Spacing", "Does", "Work!")
print "{:12}{:12}{:12}".format("Formatting", "Also", "Works!")

gives:

Spacing     Does        Work!       
Formatting  Also        Works!    

If you want them right justified:

print "{:>12}{:>12}{:>12}".format("Spacing", "Does", "Work!")
print "{:>12}{:>12}{:>12}".format("Formatting", "Also", "Works!")

gives:

     Spacing        Does       Work!
  Formatting        Also      Works!

See https://pyformat.info

Upvotes: 2

Related Questions