suchen

Heim  >  Fragen und Antworten  >  Hauptteil

So konvertieren Sie einen String in eine Liste in Python

So konvertieren Sie eine Zeichenfolge wie a = "我是中国人",转换成列表li =["我","是","中","国","人"]

1

2

3

<code>a = "我是一个中国人"

li = list(a)

print li</code>

Die Ausgabe ist

1

<code>['\xe6', '\x88', '\x91', '\xe6', '\x98', '\xaf', '\xe4', '\xb8', '\x80', '\xe4', '\xb8', '\xaa', '\xe4', '\xb8', '\xad', '\xe5', '\x9b', '\xbd', '\xe4', '\xba', '\xba']</code>

Ich habe es ganz einfach mit JavaScript umgesetzt

1

2

3

<code>var a = "我是中国人"

li = a.split("")

console.log(li) // >>>["我","是","中","国","人"]</code>

Sie wissen nicht, wie Sie es in Python implementieren sollen?

習慣沉默習慣沉默2872 Tage vor783

Antworte allen(5)Ich werde antworten

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-18 10:59:49

    可以先将字符串解编码成unicode, 再用list

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    <code># 第一种:

    >>> 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]

    是</code>

    Antwort
    0
  • 迷茫

    迷茫2017-05-18 10:59:49

    用python3

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-05-18 10:59:49

    python3没有编码问题

    1

    2

    3

    4

    5

    6

    7

    <code>In [20]: a

    Out[20]: '我是中国人'

     

    In [21]: li=list(a)

     

    In [22]: li

    Out[22]: ['我', '是', '中', '国', '人']</code>

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-05-18 10:59:49

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    <code class="python"># -*- 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]

    #>> 我

    #>> 是

    #>> 中

    #>> 国</code>

    Antwort
    0
  • 高洛峰

    高洛峰2017-05-18 10:59:49

    1、不用list(a),直接

    1

    2

    3

    <code>for each in a:  

        print each

          </code>

    这样就可以,和编码没关系,和python2或python3也没关系

    2、可以把a直接当作一个list了,取得话就用 a[num]切片就可以,比如取“我”就是a[0],取“中国”可以用a[2:3]

    Antwort
    0
  • StornierenAntwort