0

如果我想要mystring = (any number between 0-9)有什么方法可以将这样的值分配给字符串?

如果我有类似的东西:

mystring = "7676-[0-9]-*"

我希望这在理论上等于 7676-5-0 和 7676-9-100 等。我想要这个的原因是因为稍后在我的脚本中我将编写一个条件语句,例如:

if mystring == yourstring:
    print('something cool')
else:
    print('not cool')

whereyourstring等于一个数字,例如7676-3-898它等于mystring7777-7-8不等于的地方mystring

4

2 回答 2

0

您正在寻找正则表达式

例如,这应该对您有用:

import re
# 7676 + one digit between 0 and 9 + at least one digit between 0 and 9 (can be more)
pattern = "7676-[0-9]-[0-9]+"

稍后在您的代码中:

if re.match(pattern, "7676-9-100"):
    print("something cool")
else:
    print("not cool")
于 2020-07-27T14:38:09.723 回答
0

作为正则表达式版本的替代方案,您可以使用 Python 中的 split() 函数以 Pythonic 方式实现此目的:

    mystring = "7676-5-*"
    if '0' <= mystring.split('-')[1] <= '9':
        print('something cool')
    else:
        print('not cool')
于 2020-07-27T14:40:11.280 回答