You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python切片从电话号码列表提取国家码并实现搜索

问题:提取电话号码国家码并实现搜索(要求使用切片操作)

需求说明

  • 编写Python脚本,从给定的电话号码列表中提取国家码
  • 支持通过输入的国家码,筛选出对应的电话号码
  • 必须使用**切片(slice)**操作完成核心逻辑

初始尝试代码(存在错误)

尝试提取+到第一个空格之间的内容作为国家码,但切片操作使用错误:

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)

错误点:

  • 错误地将电话号码的列表索引转为字符串,而非直接处理电话号码本身
  • 使用number["+", " "]这种不符合Python切片语法的方式,切片需要基于索引位置确定范围

修正后的正确代码

调整后实现了需求,核心通过获取+和第一个空格的索引,再用切片提取国家码:

#### ---- 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("请输入国家码搜索国际联系人: ")

#### ---- CONTACT SEARCH ---- ####
for number_string in phone_numbers:
    plus_index = number_string.index('+')
    space_index = number_string.index(' ')
    country = number_string[plus_index:space_index]
    if country_code in country:
        print(number_string)

运行示例

当输入国家码49时,输出结果:

请输入国家码搜索国际联系人: 49
+49 151 123 456
+49 764 756 242
+49 555 555 5555

内容的提问来源于Stack Exchange,提问作者Jordan Melton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 00:37:14