2024-09-30 16:34:14 发布
网友
我需要字符串中的条件替换
input_str = "a111a11b111b22" condition : ("b" + any number + "b") to ("Z" + any number) output_str = "a111a11Z11122"
也许我需要使用[0]和[-1]来删除“b”s和“Z”+任何数字
[0]
[-1]
但我找不到它的条件替换
您应该使用regular expressions。它们非常有用:
import re input_str = "a111a11b111b22" output_str = re.sub(r'b(\d+)b', r'Z\1', input_str) # output_str is "a111a11Z11122"
r'b(\d+)b'regexpr与字母b匹配,后跟1个或多个数字和其他字母b。括号存储句子替换部分(字母Z和\1)中的数字以供进一步使用
r'b(\d+)b'
b
Z
\1
尝试使用正则表达式:
import re input_str = "a111a11b111b22" output_str = re.sub(r'[b](\d)',r'Z\1',input_str) print(output_str)
您应该使用regular expressions。它们非常有用:
r'b(\d+)b'
regexpr与字母b
匹配,后跟1个或多个数字和其他字母b
。括号存储句子替换部分(字母Z
和\1
)中的数字以供进一步使用尝试使用正则表达式:
相关问题 更多 >
编程相关推荐