我正在使用 python,我希望能够打印文件并分隔值。为了添加一些上下文,我从 Json 文件中取出选定的值,更改这些值,然后将它们放回原处。我可以执行每一步...
但是我对其中一行文本遇到了问题...
"Hello, the date goes from {{exercise.start_date|pretty_date}} to {{exercise.end_date|pretty_date}}."
基本上,它的完成方式可以使用解决方法,但我的问题是,有没有一种方法可以忽略不同的部分,例如“{{”和“}}”之间的所有内容
那么我想要得到的输出将是...
"HELLO, THE DATE GOES FROM {{exercise.start_date|pretty_date}} TO {{exercise.end_date|pretty_date}}."
最佳答案
我想到的一种方法是:
st = "Hello, the date goes from {{exercise.start_date|pretty_date}} to {{exercise.end_date|pretty_date}}."
split_list = st.split() # split the string into a list
for i, sentence in enumerate(split_list):
if not sentence.startswith('{{'):
split_list[i] = sentence.upper() # make the word uppercase if it's not between '{{ }}'
print(' '.join(split_list))
这将输出所需的结果:
HELLO, THE DATE GOES FROM {{exercise.start_date|pretty_date}} TO {{exercise.end_date|pretty_date}}.
您也可以在一行中实现此目的,如 @depperm建议:
' '.join([word.upper() if not word.startswith('{{') else word for word in test.split()])
只要您没有另一个可能想要大写的 {{..}}
,此方法就可以工作
关于python - 使用分隔符时忽略字符之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40680308/