[英]Python conditional replace
我需要字符串中的條件替換。
input_str = "a111a11b111b22"
condition : ("b" + any number + "b") to ("Z" + any number)
output_str = "a111a11Z11122"
也許我需要使用[0]
和[-1]
來刪除“b”和“Z”+任何數字
但我找不到它的有條件替換。
嘗試使用正則表達式:
import re
input_str = "a111a11b111b22"
output_str = re.sub(r'[b](\d)',r'Z\1',input_str)
print(output_str)
您應該使用正則表達式。 它們真的很有用:
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
。 括號記憶數字以供進一步使用(與\\1
在句子(字母的更換部件) Z
和\\1
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.