繁体   English   中英

将电话号码拆分为数字列表:Python

[英]Splitting a Phone Number into a List of Digits: Python

我目前正在尝试将应该是电话号码的字符串拆分成仅包含单个数字的列表。 我这样做是为了对用户输入信息的字段进行错误校验。

例如:

如果用户输入:123 456-7890

我想输出列表:[1,2,3,4,5,6,7,8,9,0]

我目前正在跑步:

numbersList = [int(s) for s in str.split(unformattedPhone) if s.isdigit()]

但是,这通过将920视为一个单独的数字而一直挂断电话,并且也不用连字符分开。 我认为有办法使用正则表达式来做到这一点,但我对此并不满意。 任何建议表示赞赏,谢谢。

遍历字符串。

例如:

unformattedPhone = "123 456-7890"
numbersList = [int(s) for s in unformattedPhone if s.isdigit()]
print(numbersList)

输出”

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

您可以使用re.findall

import re
s = '123 456-7890'
new_s = [int(i) for i in re.findall('\d', s)]

输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

您也可以删除所有非数字\\D

import re
unformattedPhone = "123 456-7890"
nrs = [int(i) for i in re.sub('\D', '', unformattedPhone)]
print(nrs)

产量

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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