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

前端 未结 13 1229
一整个雨季
一整个雨季 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:09
    from itertools import chain
    
    string = 'your string'
    chain(string)
    

    similar to list(string) but returns a generator that is lazily evaluated at point of use, so memory efficient.

    0 讨论(0)
  • 2020-11-22 02:11

    You take the string and pass it to list()

    s = "mystring"
    l = list(s)
    print l
    
    0 讨论(0)
  • 2020-11-22 02:11

    You can also do it in this very simple way without list():

    >>> [c for c in "foobar"]
    ['f', 'o', 'o', 'b', 'a', 'r']
    
    0 讨论(0)
  • 2020-11-22 02:11

    You can use extend method in list operations as well.

    >>> list1 = []
    >>> list1.extend('somestring')
    >>> list1
    ['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 02:15

    I you just need an array of chars:

    arr = list(str)
    

    If you want to split the str by a particular str:

    # str = "temp//temps" will will be ['temp', 'temps']
    arr = str.split("//")
    
    0 讨论(0)
提交回复
热议问题