我怎样才能以更高效的 python 友好方式执行以下操作?
first_team= re.sub("Northern", "N", first_team)
first_team=re.sub("Western", "W", first_team)
first_team=re.sub("Southern", "S", first_team)
first_team=re.sub("Eastern", "E", first_team)
最佳答案
使用 for 循环:
for direction in ('Northern', 'Western', 'Southern', 'Eastern'):
first_team = first_team.replace(direction, direction[0])
这里不需要使用re.sub
来处理这种简单的替换:), str.replace
非常好。
关于Pythonic 字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18590190/