python - 使用分隔符时忽略字符之间

标签 python json

我正在使用 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/

相关文章:

python - 导入错误: No module named fixedpickle when running PyDsTool on Windows 7

python - 如何在 Python 中创建 JSON 可编码动态字符串

javascript - 获取 json 数据在 IE 中有效,但在 FF 和 Chrome 中无效

Python-无法使用 BeautifulSoup 定位 CSS 类

python - 有没有办法暂停 Python 子进程,特别是在 Ubuntu 中?

python - 使用python中的任务队列在google appengine中进行异步调用

json - 错误 错误 : getaddrinfo ENOTFOUND - mysql

javascript - 在 AngularJS 中为 jQuery 日期选择器动态设置最大限制

java - Jackson 从根数组中获取 key 的值

python - 当我运行我的网络时。我收到错误,梯度计算所需的变量之一已被就地操作修改