I actually know how to do this using loop
, but the code looks too ugly :-(. So I would like to ask some better methods.
E.g. 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, e.g. because someone did something terrible like list = [1,2,3]
).
All other approaches (e.g. no-op list comprehensions) are slower, uglier versions of these two.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With