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

如何用Python re模块匹配以M开头且仅含1个i/I的美国州名

代码问题修复与实现

原代码存在的问题

  • 列表m_word初始化逻辑错误,初始值为[''],遍历过程中会出现索引越界报错
  • re.search('^M',state)返回的是正则匹配对象而非州名字符串,后续统计i出现次数时会直接报错
  • 统计i的出现次数时未忽略大小写,无法匹配大写I
  • 循环嵌套逻辑混乱,无意义重复遍历列表,会导致重复打印或漏打印结果

修复后代码

实现思路

遍历所有州名,先判断首字母是否为M,再统计字符串中i/I的总出现次数,输出次数等于1的州名即可:

state_names=['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut',
'Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana',
'Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts',
'Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada',
'New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio',
'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee',
'Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin',
'Wyoming']

result = []
for state in state_names:
    # 筛选首字母为M的州
    if not state.startswith('M'):
        continue
    # 统计i/I的出现次数
    i_count = state.lower().count('i')
    if i_count == 1:
        result.append(state)

# 打印符合条件的州名
for item in result:
    print(item)

如果想用正则表达式直接匹配,也可以用更简洁的写法:

import re
pattern = r'^M[^iI]*[iI][^iI]*$'
for state in state_names:
    if re.fullmatch(pattern, state):
        print(state)

运行结果

输出符合条件的州名:

  • Minnesota

内容的提问来源于stack exchange,提问作者안은아

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:15:07