我有以下代码:
stru = "۰۱۲۳۴۵۶۷۸۹"
strlist = stru.decode("utf-8").split()
print strlist[0]
我的输出是:
۰۱۲۳۴۵۶۷۸۹
但是当我使用:
print strlist[1]
我得到了以下的traceback
:
IndexError: list index out of range
我的问题是,我如何分割
我的字符串
?当然,记得我从一个函数
中获取我的字符串
,将其视为一个变量
?
我有以下代码:
stru = "۰۱۲۳۴۵۶۷۸۹"
strlist = stru.decode("utf-8").split()
print strlist[0]
我的输出是:
۰۱۲۳۴۵۶۷۸۹
但是当我使用:
print strlist[1]
我得到了以下的traceback
:
IndexError: list index out of range
我的问题是,我如何分割
我的字符串
?当然,记得我从一个函数
中获取我的字符串
,将其视为一个变量
?
你不需要这样做。
>>> print u"۰۱۲۳۴۵۶۷۸۹"[1]
۱
如果你仍然想要...
>>> list(u"۰۱۲۳۴۵۶۷۸۹")
[u'\u06f0', u'\u06f1', u'\u06f2', u'\u06f3', u'\u06f4', u'\u06f5', u'\u06f6', u'\u06f7', u'\u06f8', u'\u06f9']
split()
方法默认按空格拆分字符串。因此,strlist
是一个包含整个字符串的列表,而且只有一个元素 strlist[0]
。
如果您想获得每个 Unicode 代码点的单独元素列表,可以通过不同的方式将其转换为列表:
list(stru.decode("utf-8"))
[item for item in stru.decode("utf-8")]
for character in stru.decode("utf-8"):
...)list(stru.decode("utf-8"))
strlist = [s for s in stru.decode('utf-8')]
- Shashank