简体   繁体   中英

Special characters break alignment in formatting

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 ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM