2016-11-18 42 views
1

我使用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}}." 

回答

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()]) 

只要你不会有另一个{{..}},你可能想大写

+1

在一行是:'''.join([word.upper()if not word.startswith('{{ ')else test.split()]中的单词)' – depperm

+0

是的,这是正确的。我还在你的答案中加了一行。我希望你不介意:) – 2016-11-18 15:29:25

+0

不,我的工作就行了理解的方式,但它是相同的逻辑,你 – depperm

相关问题