Pythonic 字符串操作

标签 python string dictionary

我怎样才能以更高效的 p​​ython 友好方式执行以下操作?

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/

相关文章:

python - 从字典中分配和调用内置函数 (Python)

python - 拍卖脚本(从文件输入到字典)

python - 为什么 NumPy 和 SciPy 有很多相同的函数?我应该更喜欢哪个?

python - 在 python 中求解 (m choose x) = n 的高效算法

c# - 用于从字符串中删除字符序列的String方法

python - 如何从 k :v tuples returned from a SQL query? 列表创建字典

python - 使用 Python 记录拖尾守护进程

python - django Wagtail 嵌入视频未显示

c++ - 减少C++中的字符串容量

java - 字符串 while 循环