Python Jinja 将字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39938323/
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-08-19 22:57:17  来源:igfitidea点击:

Jinja convert string to integer

pythonansiblejinja2

提问by SJC

I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.

我正在尝试将使用正则表达式解析的字符串转换为数字,以便我可以使用 Jinja2 将其相乘。此文件是要在 ansible 脚本中使用的模板。

I have a series of itemswhich all take the form of <word><number>such as aaa01, aaa141, bbb05.

我有一系列items都采用<word><number>诸如aaa01, aaa141,的形式bbb05

The idea was to parse the word and number(ignoring leading zeros) and use them later in the template.

这个想法是解析单词和数字(忽略前导零)并稍后在模板中使用它们。

I wanted to manipulate the number by multiplication and use it. Below is what I have done so far ```

我想通过乘法来操纵数字并使用它。以下是我到目前为止所做的```

{% macro get_host_number() -%}
{{ item | regex_replace('^\D*[0]?(\d*)$', '\1') }}
{%- endmacro %}

{% macro get_host_name() -%}
{{ item | regex_replace('^(\D*)\d*$', '\1') }}
{%- endmacro %}

{% macro get_host_range(name, number) -%}
{% if name=='aaa' %}
{{ ((number*5)+100) | int | abs }}
{% elif name=='bbb' %}
{{ ((number*5)+200) | int | abs }}
{% else %}
{{ ((number*5)+300) | int | abs }}
{% endif %}
{%- endmacro %}

{% set number = get_host_number() %}
{% set name = get_host_name() %}
{% set value = get_host_range(name, number) %}

Name: {{ name }}
Number: {{ number }}
Type: {{ value }}

With the above template I am getting an error coercing to Unicode: need string or buffer, int foundwhich i think is telling me it cannot convert the string to integer, however i do not understand why. I have seen examples doing this and working.

使用上面的模板,我收到一个错误coercing to Unicode: need string or buffer, int found,我认为它告诉我它无法将字符串转换为整数,但是我不明白为什么。我见过这样做的例子并且工作。

回答by Konstantin Suvorov

You need to cast string to int after regex'ing number:

您需要在 regex'ing number 后将 string 转换为 int:

{% set number = get_host_number() | int %}

And then there is no need in | intinside get_host_rangemacro.

然后就不需要| int内部get_host_range宏了。