我正在使用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}}."
答案 0 :(得分:1)
我想到的一种做法是:
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()])
只要你没有另外{{..}}
你可能希望成为大写