Reputation: 1242
Aloha, i've some strings which i'm nicely formatting with str.format()
this way:
strings = [
'Aloha',
'SomeString',
'Special ´ char',
'Numb3rsAndStuff'
]
for string in strings:
print('> {:<20} | more text <'.format(string))
This gives me this output:
Aloha | more text <
strings | more text <
Special ´ char | more text <
Numb3rs | more text <
As you can see, the special character breaks the alignment. What can i do about this? I don't want this disrcrepancy ...
Upvotes: 2
Views: 1143
Reputation: 59228
Python 2 exhibits this problem if you are using ordinary strings, because the special character you included is represented by the two characters '\xc2\xb4'
, taking up two spaces. It will work ok if you use unicode strings. That involves putting a u
in front of your string literals.
strings = [
u'Aloha',
u'SomeString',
u'Special ´ char',
u'Numb3rsAndStuff'
]
for string in strings:
print(u'> {:<20} | more text <'.format(string))
Output:
Aloha | more text <
SomeString | more text <
Special ´ char | more text <
Numb3rsAndStuff | more text <
In Python 3 this wouldn't happen because all the strings are unicode strings.
Upvotes: 4