gpt4 book ai didi

python - Python中字符串的第一个字符

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:08 24 4
gpt4 key购买 nike

在 Python 中我得到了这个字符串

string = "Ľubomír Mezovský"

我只需要获取它的第一个字符。但是当我尝试 string[0] 时,它返回了 。当我尝试 string[:2] 时,它运行良好。我的问题是为什么?我需要为几个字符串运行它,当字符串不以变音符号开头时,它返回两个字符的子字符串。

我也在使用 # encoding=utf8 和 Python 2.7

最佳答案

您正在处理字节串(假设您使用的是 Python 2.x)。

使用 str.decode 将字节串转换为 unicode 串,获取第一个字符,然后使用 str.encode 将其转换回二进制字符串(可选,除非你应该使用字节串)

>>> string = "Ľubomír Mezovský"
>>> print(string.decode('utf-8')[0].encode('utf-8'))
Ľ

关于python - Python中字符串的第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49386034/

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