gpt4 book ai didi

python - 特殊字符会破坏格式对齐

转载 作者:行者123 更新时间:2023-11-28 22:46:21 26 4
gpt4 key购买 nike

Aloha,我有一些字符串,我正在用 str.format() 很好地格式化它们这样:

strings = [
'Aloha',
'SomeString',
'Special ´ char',
'Numb3rsAndStuff'
]

for string in strings:
print('> {:<20} | more text <'.format(string))

这给了我这个输出:

Aloha                | more text <
strings | more text <
Special ´ char | more text <
Numb3rs | more text <

如您所见,特殊字符破坏了对齐。我该怎么办?我不想要这种差异......

最佳答案

如果您使用普通字符串,Python 2 会出现此问题,因为您包含的特殊字符由两个字符 '\xc2\xb4' 表示,占用两个空格。如果你使用 unicode 字符串,它会工作正常。这涉及在字符串文字前放置一个 u

strings = [
u'Aloha',
u'SomeString',
u'Special ´ char',
u'Numb3rsAndStuff'
]

for string in strings:
print(u'> {:<20} | more text <'.format(string))

输出:

Aloha                | more text <
SomeString | more text <
Special ´ char | more text <
Numb3rsAndStuff | more text <

在 Python 3 中,这不会发生,因为所有字符串都是 unicode 字符串。

关于python - 特殊字符会破坏格式对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com