python - Python 条件替换
问题描述
我需要在字符串中进行条件替换。
input_str = "a111a11b111b22"
condition : ("b" + any number + "b") to ("Z" + any number)
output_str = "a111a11Z11122"
也许我需要使用 [0]
and[-1]
删除“b”和“Z”+任何数字
但我找不到它的条件替换。
解决方案
尝试使用正则表达式:
import re
input_str = "a111a11b111b22"
output_str = re.sub(r'[b](\d)',r'Z\1',input_str)
print(output_str)
推荐阅读
- python - 如何仅在错误时获取所有 Python 日志?
- windows - Windows 上的 CMake 共享库:创建 dll 时出错
- docker - docker push 到我的公司 docker 存储库
- asp.net-core - 是否可以添加角度或对现有的 asp.net core 2.1 应用程序作为解决方案中的隔离项目做出反应?
- php - 如何将销售价格四舍五入到小数点后一位?
- java - 获取与 aa Treepath 关联的 DefaultMutableTreeNode(确切的不是临时的)
- javascript - 如何通过循环函数将 N 个数组的所有数组变量推送到一个数组中?
- java - 具有可变参数参数的多个构造函数
- c# - 如何在 Azure Cosmos DB(BotFramework)中存储 UserState 和 ConversationState?
- rust - 是否可以将 char 值分配给枚举变体?