Heim > Fragen und Antworten > Hauptteil
So konvertieren Sie eine Zeichenfolge wie a = "我是中国人"
,转换成列表li =["我","是","中","国","人"]
a = "我是一个中国人"
li = list(a)
print li
Die Ausgabe ist
['\xe6', '\x88', '\x91', '\xe6', '\x98', '\xaf', '\xe4', '\xb8', '\x80', '\xe4', '\xb8', '\xaa', '\xe4', '\xb8', '\xad', '\xe5', '\x9b', '\xbd', '\xe4', '\xba', '\xba']
Ich habe es ganz einfach mit JavaScript umgesetzt
var a = "我是中国人"
li = a.split("")
console.log(li) // >>>["我","是","中","国","人"]
Sie wissen nicht, wie Sie es in Python implementieren sollen?
曾经蜡笔没有小新2017-05-18 10:59:49
可以先将字符串解编码成unicode
, 再用list
# 第一种:
>>> a = u"我是中国人"
>>> s = list(a)
>>> print s
[u'\u6211', u'\u662f', u'\u4e2d', u'\u56fd', u'\u4eba']
>>> print s[1]
是
# 第二种
>>> a = "我是中国人"
>>> s = a.decode('utf8')
>>> s = list(a.decode('utf8'))
>>> s
[u'\u6211', u'\u662f', u'\u4e2d', u'\u56fd', u'\u4eba']
>>> print s[1]
是
巴扎黑2017-05-18 10:59:49
python3没有编码问题
In [20]: a
Out[20]: '我是中国人'
In [21]: li=list(a)
In [22]: li
Out[22]: ['我', '是', '中', '国', '人']
天蓬老师2017-05-18 10:59:49
# -*- coding: utf-8 -*-
def unicode_chars(s):
if not isinstance(s, unicode):
s = s.decode("utf-8")
return [c for c in s]
print unicode_chars("我是中国人")[0]
print unicode_chars(u"我是中国人")[1]
print unicode_chars(r"我是中国人")[2]
print unicode_chars(b"我是中国人")[3]
#>> 我
#>> 是
#>> 中
#>> 国
高洛峰2017-05-18 10:59:49
1、不用list(a),直接
for each in a:
print each
这样就可以,和编码没关系,和python2或python3也没关系
2、可以把a直接当作一个list了,取得话就用 a[num]切片就可以,比如取“我”就是a[0],取“中国”可以用a[2:3]