string Jinja2 用空格分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20678004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:11:52  来源:igfitidea点击:

Jinja2 Split string by white spaces

stringsplitjinja2

提问by elad.chen

I'm using Jinja2 template engine (+pelican).

我正在使用 Jinja2 模板引擎 (+pelican)。

I have a string saying "a 1", and I am looking for a way to split that string in two by using the white-space as the delimiter.

我有一个字符串,上面写着“a 1”,我正在寻找一种方法,通过使用空格作为分隔符将该字符串一分为二。

So the end result I'm looking for is a variable which holds the two values in a form of an array. e.g. str[0] evaluates to "a" & str[1] evaluates to "1".

所以我要寻找的最终结果是一个变量,它以数组的形式保存两个值。例如,str[0] 的计算结果为“a”,而 str[1] 的计算结果为“1”。

Thanks in advance.

提前致谢。

采纳答案by Lo?c

I had the same issue and didn't find anything useful, so I just created a custom filter :

我遇到了同样的问题并且没有发现任何有用的东西,所以我刚刚创建了一个自定义过滤器:

def split_space(string):
    return string.strip().split()

Added it to the filter list (with flask):

将其添加到过滤器列表(带烧瓶):

app = Flask(__name__)

def split_space(string):
    return string.strip().split()

#some code here

if __name__ == '__main__':

    app.jinja_env.filters['split_space'] = split_space
    app.run()

And used it as such in the template :

并在模板中使用它:

{% if "string" in element|split_space %} ... {% endif %}

回答by Jakub Kotowski

Calling split on the string should do the trick:

在字符串上调用 split 应该可以解决问题:

"a 1".split()

回答by dragon

my solution is tested in iPython

我的解决方案在 iPython 中进行了测试

In [1]: from jinja2 import Template
In [2]: Template("{{s.split('-')}}").render(s='a-bad-string')
Out[2]: u"['a', 'bad', 'string']"

回答by User2403

I'd suggest to use something like:

我建议使用类似的东西:

str = "a 1 b 2 c 3"
val = atr.split()

Also, if you want to point a specific position then you can use something like:

此外,如果您想指向特定位置,则可以使用以下内容:

val1 = atr.split()[2]

This will put second value in val1.

这会将第二个值放入val1.

回答by Tim Raasveld

I made a little plugin that does the same as Lo?c's answer but it optionally specifying a separator. https://github.com/timraasveld/ansible-string-split-filter

我制作了一个与 Lo?c 的答案相同的小插件,但它可以选择指定一个分隔符。https://github.com/timraasveld/ansible-string-split-filter

It allows you to type:

它允许您键入:

# my_variable = 'a 1`
{ my_variable | split | join(' and ') } #=> a and 1

回答by Jeremy Jones

You can also do this with a decorator:

你也可以用装饰器来做到这一点:

from flask import Flask
app = Flask(__name__)

@app.template_filter('split_space')
def split_space_filter(s):
    return s.strip().split()

if __name__ == '__main__':
    app.run()