简体   繁体   中英

Python: Better way to take every letter/number/etc. from a string and convert it into a list?

I actually know how to do this using loop , but the code looks too ugly :-(. So I would like to ask some better methods.

Eg I have a string:

a = "123 456 7sr"

I want to convert every number/letter/empty space/etc into a list. The desired result should be like:

["1", "2", "3", " ", "4", "5", "6", " ", "7", "s", "r"]

Is there some other methods? (Please not the methods using the for/while loop )

Thanks for the help!

Straightforward approach that works everywhere is to call list 's constructor, which converts any iterable (and str are iterables of their characters) to a list of the values produced by iterating:

list(a)

On Python 3.5+ with additional unpacking generalizations , you can alternatively do:

[*a]

which is equivalent to list(a) , except it doesn't need to look up and call the list constructor through generalized function call semantics (making it slightly faster and rendering it immune to accidental behavioral changes if list is name shadowed, eg because someone did something terrible like list = [1,2,3] ).

All other approaches (eg no-op list comprehensions) are slower, uglier versions of these two.

That's simply:

>>> a = "123 456 7sr"
>>> list(a)
['1', '2', '3', ' ', '4', '5', '6', ' ', '7', 's', 'r']

This might not be better, but an alternative approach would be to use a list comprehension:

a = "123 456 7sr"
print([e for e in a])

Output:

['1', '2', '3', ' ', '4', '5', '6', ' ', '7', 's', 'r']

Strings are iteratable elements so pass the iteratable to the list's constructor then it will return a list.

>>a="123 456 7sr"
>>a=list(a)
>>print(a)
>>['1', '2', '3', ' ', '4', '5', '6', ' ', '7', 's', 'r']
>>print(type(a))
>>list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM