【问题标题】:Condition if string contains only variable and integer Python条件如果字符串仅包含变量和整数 Python
【发布时间】:2013-03-14 02:54:16
【问题描述】:

所以,我正在编写 Python 3 中的脚本,我需要这样的东西

control_input=input(prompt_029)
if only string_029 and int in control_input:
    #do something
else:
    #do something else

基本上,我要求的代码条件如下:

if control_input == "[EXACT_string_here] [ANY_integer_here]"

代码在 Python 3 中会是什么样子?

【问题讨论】:

标签: python regex string integer conditional-statements


【解决方案1】:

你想要的是做一个regular expression 匹配。看看re module。

>>> import re
>>> control_input="prompt_029"
>>> if re.match('^prompt_[0-9]+$',control_input):
...     print("Matches Format")
... else:
...     print("Doesn't Match Format")
... 
Matches Format

正则表达式^prompt_[0-9]+$ 匹配以下内容:

^        # The start of the string 
prompt_  # The literal string 'prompt_'
[0-9]+   # One or more digit 
$        # The end of the string 

如果数字必须包含三个数字,那么您可以使用^prompt_[0-9]{3}$ 或最多三个然后尝试^prompt_[0-9]{1,3}$。

【讨论】:

    【解决方案2】:

    没有正则表达式

    >>> myvar = raw_input("input: ")
    input: string 1
    >>> myvar
    'string 1'
    >>> string, integer = myvar.strip().split()
    >>> "[EXACT_string_here] [ANY_integer_here]" == "{} {}".format(string, integer)
    True
    

    【讨论】:

    • 这并没有真正做到 OP 所要求的 - 输入中的整数部分是可变的,而不是始终为 1,并且没有直接的方法来修改您的代码以允许这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2015-02-08
    • 2021-12-31
    • 2017-11-04
    • 2014-10-30
    相关资源
    最近更新 更多