将字符串(不带任何分隔符)转换为列表 [英] Convert string (without any separator) to list
问题描述
我有一个电话号码(字符串),例如我想将其变成"+ 123-456-7890",该列表看起来像:[+,1,2,3,-,....,0].
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 the list and remove all the symbols, so I'm left with a list of only digits, which I can then convert back to a string.
解决此问题的最佳方法是什么?我遇到的所有解决方案均不适用,因为在数字之间没有任何特殊字符(因此我无法在其中分割字符串).
What's the best way to solve this problem? None of the solutions I've come across are applicable, because I don't have any special characters in-between the digits (so I can't split the string there.)
有什么想法吗?我真的很感激!
Any ideas? I really appreciate it!
编辑-这是我尝试过的:
Edit - this is what I've tried:
x = row.translate(None, string.digits)
list = x.split()
也:
filter(lambda x: x isdigit())
推荐答案
您的意思是您想要类似的东西:
You mean that you want something like:
''.join(n for n in phone_str if n.isdigit())
这利用了字符串可迭代的事实.当您遍历它们时,它们每次产生1个字符.
This uses the fact that strings are iterable. They yield 1 character at a time when you iterate over them.
关于您的努力
该字符实际上从字符串中删除了所有数字,只剩下非数字.
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()
这篇关于将字符串(不带任何分隔符)转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!