How to convert a string such as a = "I am Chinese"
into a list li =["I","是","中","国","人"]
a = "我是一个中国人"
li = list(a)
print li
The output is
['\xe6', '\x88', '\x91', '\xe6', '\x98', '\xaf', '\xe4', '\xb8', '\x80', '\xe4', '\xb8', '\xaa', '\xe4', '\xb8', '\xad', '\xe5', '\x9b', '\xbd', '\xe4', '\xba', '\xba']
I implemented it very simply using JavaScript
var a = "我是中国人"
li = a.split("")
console.log(li) // >>>["我","是","中","国","人"]
Don’t know how to implement it in python?
曾经蜡笔没有小新2017-05-18 10:59:49
You can first decode the string into 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 has no encoding issues
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. No need to list(a), just
for each in a:
print each
That’s it, it has nothing to do with coding, nor does it have to do with python2 or python3
2. You can directly treat a as a list. To obtain it, just use a[num] to slice it. For example, to obtain "I", it is a[0], and to obtain "China", you can use a[2:3]