首页 > 解决方案 > 可以使用字典从字符串 Python 的开头删除多个字符吗?

问题描述

我目前正在进行爱尔兰电话号码格式的工作。有许多不同的字符需要从一开始就被删除。这是代码的一个小示例。我想知道是否有另一种方法可以像字典一样执行此操作,使其为 [353:3, 00353:5, 0353:4...] 并根据匹配字符串的长度对开头进行切片?提前致谢。

if s.startswith("353") == True:
    s = s[3:]
if s.startswith("00353") == True:
    s = s[5:]
if s.startswith("0353") == True:
    s = s[4:] 
if s.startswith("00") == True:
    s = s[2:]    

标签: pythondictionarydata-cleaning

解决方案


你可以做这样的事情,如果找到的话,用空字符串替换开头。

s = "00353541635351651651"

def remove_prefix(string):
    starters = ["353", "00353", "0353", "00"]
    for start in starters:
        if string.startswith(start):
            return string.replace(start, "")

print(remove_prefix(s))

推荐阅读