D. Cox D. Cox - 1 year ago 53
JSON Question

ignore between characters while using a delimiter

I'm working with python and I want to be able to print off a file and separate the values. To add some context, I'm taking selected values out of a Json file, changing the values and then putting them back in. I can do every step...

But I'm having an issue with one of the lines of text...

"Hello, the date goes from {{exercise.start_date|pretty_date}} to {{exercise.end_date|pretty_date}}."

Basically the way that it's been done works with a workaround, but my question is, is there a way that I can ignore different sections, for example everything in between '{{' and '}}'

Then the output I want to get would be...

"HELLO, THE DATE GOES FROM {{exercise.start_date|pretty_date}} TO {{exercise.end_date|pretty_date}}."

Answer Source

One way of doing this that come to my mind is:

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

Which will output the desired result:

HELLO, THE DATE GOES FROM {{exercise.start_date|pretty_date}} TO

You could also achieve this in one line as @depperm suggested:

' '.join([word.upper() if not word.startswith('{{') else word for word in test.split()])

This will work as long as you won't have another {{..}} that you may want to be uppercase