python - 可以使用字典从字符串 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:]
解决方案
你可以做这样的事情,如果找到的话,用空字符串替换开头。
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))
推荐阅读
- ios - 错误链接器命令失败,退出代码为 1(Paytm 支付集成时)
- python - Registry cannot be found, Outlook Security
- android - 应如何为具有多个字段的活动实现 ViewModel
- android - 毕加索不在片段中工作
- loops - 切片指针和循环
- django - 如何根据请求数据过滤 DRF 序列化程序 HyperlinkedRelationField 查询集?
- wordpress - 使用 capistrano 部署 wordpress 站点
- powershell - 如何从文件夹中选择内容中包含特定单词的文件?
- c# - 通过 HTTP 调用 RESTFUL (GET) Web API 时出现 500 服务器错误
- json - Jackson2JsonMessageConverter 以特定模式序列化 LocalDateTime