提问人:Jordan Melton 提问时间:5/13/2023 最后编辑:Jordan Melton 更新时间:5/13/2023 访问量:94
如何在 Python 中将国家/地区代码从电话号码列表中添加到列表中
how to add country codes to a list from a list of phone numbers in python
问:
我需要创建一个脚本,在其中获取电话号码列表,并能够使用其区号搜索这些电话号码。唯一的要求是我必须使用切片。任何帮助将不胜感激!
phone_numbers = ["+1 709 239 5000", "+49 151 123 456", "+64 21 202 4961", "+679 324 4362", "+1 834 721 4975", "+1 257 534 2131", "+49 764 756 242", "+679 444 0193", "+49 555 555 5555"]
country_code = input("Search your international contacts by country code: ")
country_codes = []
for i in phone_numbers:
number = str(phone_numbers.index(i))
area_code = number["+", " "]
print(area_code)
我试图切开“+”和第一个空格,并将它们添加到列表中,但我想我搞砸了使用切片。
编辑:我想我有点不擅长解释我想要什么,但回答的人基本上是正确的!我不得不稍微改变它才能得到我想要的东西,但它有效!
法典:
#### ---- SETUP ---- ####
phone_numbers = ["+1 709 239 5000", "+49 151 123 456", "+64 21 202 4961", "+679 324 4362", "+1 834 721 4975", "+1 257 534 2131", "+49 764 756 242", "+679 444 0193", "+49 555 555 5555"]
country_code = input("Search your international contacts by country code: ")
#### ---- CONTACT SEARCH ---- ####
for number_string in phone_numbers:
plus_index = number_string.index('+')
space_index = number_string.index(' ')
cuntry = number_string[plus_index:space_index]
if country_code in cuntry:
print(number_string)
输出:(输入 49)
Search your international contacts by country code: 49
+49 151 123 456
+49 764 756 242
+49 555 555 5555
答:
我想我理解你想做什么,但你当前的代码并没有真正正确地完成大部分步骤。,在您的代码中将进行第一次迭代,因为 是列表中的第一个字符串 (索引)。 根本没有任何意义,因为你不能使用字符串元组作为另一个字符串的索引。我认为您希望代码的几乎所有部分都以不同的方式排列。number
'0'
i
0
phone_numbers
number["+", " "]
尝试更像这样的东西:
phone_numbers = ["+1 709 239 5000", "+49 151 123 456", "+64 21 202 4961", "+679 324 4362", "+1 834 721 4975", "+1 257 534 2131", "+49 764 756 242", "+679 444 0193", "+49 555 555 5555"]
for number_string in phone_numbers:
plus_index = number_string.index('+')
space_index = number_string.index(' ')
country_code = number_string[plus_index:space_index]
# do whatever you want to do with country_code here, e.g. printing
print(country_code)
如果您不希望加号字符成为要保存的国家/地区代码的一部分,则可以在执行切片时将加号添加到值中。plus_index
请注意,我在此处显示的代码与您在原始代码中写给用户的提示并不匹配。如果你想搜索一个特定的代码,你可能不需要做你似乎想要的切片。相反,您可以检查,然后在匹配的情况下做任何您想做的事情。运算符执行子字符串搜索,如果您始终为国家/地区代码提供前缀,则它应该只与实际的国家/地区代码匹配,而不是字符串的其他随机部分(如有必要,您可以添加一些验证步骤以确保查询在开始搜索之前有效)。您也可以使用仅匹配前缀字符串,而不是可能在较大数字的任何位置找到任何加号前缀的子字符串。if query_country_code in number_string:
in
+
str.startswith
在这里,我们可以使用 str 类的内置方法 .split(),它将特定值上的字符串拆分为分隔符。
我们使用分隔符参数作为空格字符 “ ” ,并且还使用 Maxsplit 参数并将其设置为 1,以便仅限制在所提供字符串的第一个空格上进行拆分。
for number in phone_numbers :
code , number = number.split(" ", 1)
print(code)
如果要求是使用字符串索引切片,我们可以手动完成,只需在字符串中找到第一个空格的索引,并在此索引之前结束我们的国家代码。
for number in phone_numbers :
space_idx = number.find(" ")
code = number[:space_idx]
print(code)
评论
number[start:end]
for number, i in enumerate(phone_numbers):
i
number
1
709
for i in range(numbers): number = numbers[i]
for number in numbers