Convert string (without any separator) to list

前端 未结 9 1853
挽巷
挽巷 2020-12-09 17:09

I have a phone number(string), e.g. \"+123-456-7890\", that I want to turn into a list that looks like: [+, 1, 2, 3, -, ...., 0].

Why? So I can go iterate through t

9条回答
  •  轮回少年
    2020-12-09 17:28

    You mean that you want something like:

    ''.join(n for n in phone_str if n.isdigit())
    

    This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.


    Regarding your efforts,

    This one actually removes all of the digits from the string leaving you with only non-digits.

    x = row.translate(None, string.digits)
    

    This one splits the string on runs of whitespace, not after each character:

    list = x.split()
    

提交回复
热议问题