![](/img/trans.png)
[英]Why does the exec() function work differently inside and outside of a function?
[英]Why does this replace function fail inside this lambda function but not outside it?
import re
input_text = "el dia 2022-12-23 o sino el dia 2022-09-23 10000-08-23" #example
date_capture_pattern = r"([12]\d*-[01]\d-[0-3]\d)(\D*?)"
#input_text = re.sub(date_capture_pattern , lambda m: print(repr(m[1])) , input_text)
input_text = re.sub(date_capture_pattern , lambda m: m[1].replace("_-_", "-", 2) , input_text)
print(repr(input_text))
使用print()
我注意到捕獲組m[1]
正確捕獲了它們,因為它能夠正確打印 3 個日期。
但是,我覺得 lambda function lambda m: m[1].replace("_-_", "-", 2)
的語法(在 python 中)有些東西不允許進行替換,也就是說,即使lambda function正確接收到信息,也無法返回。
我需要的 output 是
"el dia 2022_-_12_-_23 o sino el dia 2022_-_09_-_23 10000_-_08_-_23"
應該澄清的是,問題中的代碼不會在控制台中產生任何錯誤,但是它無法正常工作,因為它僅限於刪除原始字符串中的捕獲組
lambda function 有什么問題?
您的替換邏輯已關閉。 您應該搜索-
並替換為_-_
。 使用這個版本:
input_text = "el dia 2022-12-23 o sino el dia 2022-09-23 10000-08-23"
output = re.sub(r'[12]\d*-[01]\d-[0-3]\d', lambda m: m.group().replace("-", "_-_"), input_text)
print(output)
# el dia 2022_-_12_-_23 o sino el dia 2022_-_09_-_23 10000_-_08_-_23
另請注意,此處無需使用捕獲組。
lambda m: m[1].replace("-","_-_", 2) , input_text)
順序應該是"-"
然后是"_-_"
您也可以使用簡單的字符串 function replace()
來實現。
由於您的 input_text 是一個字符串。
input_text.replace("-","_-_")
lambda function 有什么原因嗎? 一個簡單的替換就足夠了。
input_text = "el dia 2022-12-23 o sino el dia 2022-09-23 10000-08-23"
output = input_text.replace('-', '_-_')
print(output)
el dia 2022_-_12_-_23 o sino el dia 2022_-_09_-_23 10000_-_08_-_23
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.