我的代碼:
text = '12\nx\n$79.17\n8\nx\n$118.75\n6\nx\n$158.33\n4\nx\n$237.50'
re.sub(r'(\n)', '', text)
>>>12x$79.178x$118.756x$158.334x$237.50
我的預期結果是:
<br> 12x$79.17 <br> 8x$118.75 <br> 6x$158.33 <br> 4x$237.50 <br>
我想<br>在每個整數之前添加標簽。
更新1:
text = short_des.replace('\n',' ')
>>>'12 x $79.17 8 x $118.75 6 x $158.33 4 x $237.50'
現在我想<br>在每個整數之前添加。
uj5u.com熱心網友回復:
一種選擇是使用re.sub字典來映射替換:
text = '12\nx\n$79.17\n8\nx\n$118.75\n6\nx\n$158.33\n4\nx\n$237.50'
repl = {'\nx\n': 'x', '\n': ' <br> '}
import re
out = re.sub(r'(\nx\n|\n)', lambda m: repl.get(m.group()), text)
輸出:
'12x$79.17 <br> 8x$118.75 <br> 6x$158.33 <br> 4x$237.50'
注意。因為\n它的子字串\nx\n必須在正則運算式之后才能匹配第二個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485537.html
上一篇:計算另一列中字串的出現次數
下一篇:Java 并發編程
