需要帮助使用带括号的字符串
Need Help using string with brackets
我是 python 的新手。我拼凑了一个非常有效的代码,除非我在 find_str 变量的字符串中有方括号。我尝试使用双括号,但它也不起作用。
目标是将 CSV 列表中包含 _(FAIL)_
的所有文本替换为 SUCCESS
。
这是我的代码:
import glob
import re
filenames = sorted(glob.glob('*.csv'))
filenames = filenames
for f2 in filenames:
csv_name=f2
# open your csv and read as a text string
with open(csv_name, 'r') as f:
my_csv_text = f.read()
find_str = "_(FAIL)_"
replace_str = "SUCCESS"
# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)
# open new file and save
new_csv_path = csv_name
with open(new_csv_path, 'w') as f:
f.write(new_csv_str)
看起来你需要转义括号
尝试:
find_str = "_\(FAIL\)_"
replace_str = "SUCCESS"
# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)
无需使用正则表达式,re.sub()
即可,str.replace()
即可:
find_str = "_(FAIL)_"
replace_str = "SUCCESS"
my_csv_text = 'We go through life and _(FAIL)_ and _(FAIL)_ and _(FAIL)_'
new_csv_str = my_csv_text.replace(find_str, replace_str)
print(new_csv_str)
给出:
We go through life and SUCCESS and SUCCESS and SUCCESS
我是 python 的新手。我拼凑了一个非常有效的代码,除非我在 find_str 变量的字符串中有方括号。我尝试使用双括号,但它也不起作用。
目标是将 CSV 列表中包含 _(FAIL)_
的所有文本替换为 SUCCESS
。
这是我的代码:
import glob
import re
filenames = sorted(glob.glob('*.csv'))
filenames = filenames
for f2 in filenames:
csv_name=f2
# open your csv and read as a text string
with open(csv_name, 'r') as f:
my_csv_text = f.read()
find_str = "_(FAIL)_"
replace_str = "SUCCESS"
# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)
# open new file and save
new_csv_path = csv_name
with open(new_csv_path, 'w') as f:
f.write(new_csv_str)
看起来你需要转义括号
尝试:
find_str = "_\(FAIL\)_"
replace_str = "SUCCESS"
# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)
无需使用正则表达式,re.sub()
即可,str.replace()
即可:
find_str = "_(FAIL)_"
replace_str = "SUCCESS"
my_csv_text = 'We go through life and _(FAIL)_ and _(FAIL)_ and _(FAIL)_'
new_csv_str = my_csv_text.replace(find_str, replace_str)
print(new_csv_str)
给出:
We go through life and SUCCESS and SUCCESS and SUCCESS