How to split a string into an array of characters in Python?

前端 未结 13 1243
一整个雨季
一整个雨季 2020-11-22 01:54

I\'ve tried to look around the web for answers to splitting a string into an array of characters but I can\'t seem to find a simple method

str.split(//)

13条回答
  •  遥遥无期
    2020-11-22 02:12

    I explored another two ways to accomplish this task. It may be helpful for someone.

    The first one is easy:

    In [25]: a = []
    In [26]: s = 'foobar'
    In [27]: a += s
    In [28]: a
    Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
    

    And the second one use map and lambda function. It may be appropriate for more complex tasks:

    In [36]: s = 'foobar12'
    In [37]: a = map(lambda c: c, s)
    In [38]: a
    Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']
    

    For example

    # isdigit, isspace or another facilities such as regexp may be used
    In [40]: a = map(lambda c: c if c.isalpha() else '', s)
    In [41]: a
    Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']
    

    See python docs for more methods

提交回复
热议问题