Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 969
Rt Rtt Avatar asked Dec 11 '22 08:12

Rt Rtt


1 Answers

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.

like image 173
ShadowRanger Avatar answered Apr 10 '23 11:04

ShadowRanger