可以使用字典从字符串 Python 的开头删除多个字符吗?

Can Dictionaries be used to remove a number of characters from the start of a string Python?

我目前正在处理爱尔兰 Phone 号码的格式设置问题。有许多不同的字符需要从一开始就删除。这是代码的一个小示例。我想知道是否有另一种方法可以像字典一样执行此操作,因此它是 [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:]    

您可以这样做,如果找到则用空字符串替换开头。

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))

如果这些是互斥的,您可以使用正则表达式一次检查它们。您还可以组合相似的模式,例如353, 0353, 00353 可以通过匹配多个 0 后跟 353.

来组合
import re

s = re.sub(r'^(0{0,2}353|00)', '', s)