2016-11-18 85 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

相關問題