我有一个如下所示的列表
fruit: [ 'apple','orange2','grape3apple1']
我想要如下所示的输出,并希望将其存储在另一个变量中以供进一步使用
fruit_out: [ 'apple','orange','grape3apple' ]
如果最后一个字符是数字,我希望删除该数字,如果不是,我需要按原样返回字符串。我环顾四周,没有找到任何可用的解决方案。
最佳答案
重申我对上下文的评论:
给定一个字符串变量 somevariable
,somevariable[-1]
是最后一个字符,somevariable[:-1]
是字符串不包括最后一个字符。 –
I am looking for a validation to check if the last character is indeed a number. If there is a number at in the middle it should not count for the check
Ansible 使用 Python,因此您可以使用任何 Python string method在您的 Ansible 剧本中。例如,要在值以数字结尾时执行任务,您可以编写:
- debug:
msg: Your variable ends with a number!
when: somevariable[-1].isdigit()
您可以使用正则表达式过滤器执行相同的检查:
- debug:
msg: Your variable ends with a number!
when: somevariable is search('[0-9]$')
关于Ansible 删除字符串中的最后一个字符(如果它是数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72523552/