【问题标题】:Check whether a string contains a numeric/digit/number in python在python中检查字符串是否包含数字/数字/数字
【发布时间】:2013-08-07 07:20:27
【问题描述】:

我有一个字符串,我需要检查它是否包含字符串的number/digit at the end,并且需要在字符串末尾用+1 递增number/digit

我会得到如下字符串

string2  = suppose_name_1
string3  = suppose_name_22
string4  = supp22ose45_na56me_45

我肯定会得到上述格式的字符串,例如假设_somthing + Underscore + digits

所以从上面的字符串

  1. 我需要检查一个字符串是否在下划线后的字符串末尾包含数字/数字
  2. 如果包含,则需要使用+1 递增,如下所示

    string2 = 假设名称_2

    string3 = 假设名称_23

    string4 = supp22ose45_na56me_46

我们如何在python中使用正则表达式或其他东西来做到这一点,但这应该非常快。

我已经做了类似here 的事情,但是想用 re 来实现,这将非常快,所以接近了

Edit: 对不起,上面没有提到

有时它只包含something_name 没有整数,因此我需要先检查它是否包含数字

【问题讨论】:

  • 您说您的字符串肯定会采用那种格式?那为什么要检查字符串是否以数字结尾?

标签: python string digit


【解决方案1】:

如何使用正则表达式:

import re

def process_string(s):
    try:
        part1, part2 = re.search('^(.*_)(\d+)$', s).groups()
        part2 = str(int(part2) + 1)
        return part1 + part2 
    except AttributeError:
        return s

print process_string("suppose_name_1")
print process_string("suppose_name_22")
print process_string("supp22ose45_na56me_45")

print process_string("suppose_name")

打印:

suppose_name_2
suppose_name_23
supp22ose45_na56me_46
suppose_name

仅供参考,使用正则表达式并没有错或可怕。

【讨论】:

    【解决方案2】:

    您不需要正则表达式。你可以用简单的str.replace:

    >>> s = 'suppose_name_1'
    >>> index = s.rfind('_')  # Last index of '_'
    >>> s.replace(s[index+1:], str(int(s[index+1:]) + 1))
    'suppose_name_2'
    

    如果需要先检查末尾是否有数字,可以使用str.isdigit()方法检查:

    >>> s = 'suppose_name'
    >>> 
    >>> index = s.rfind('_')
    >>> if s[index+1:].isdigit():
            s = s.replace(s[index+1:], str(int(s[index+1:]) + 1))
    
    
    >>> s
    'suppose_name'
    

    【讨论】:

    • k rohit,但很抱歉我在问题中提到了有时我会在最后得到没有数字的假设名称,所以首先我需要检查它是否包含整数。
    • @shivakrishna。已编辑帖子。
    【解决方案3】:

    这里是用 re.sub(...) 递增数字的简短正则表达式解决方案:

    from re import sub
    
    string2  = 'suppose_name_1'
    string3  = 'suppose_name_22'
    string4  = 'supp22ose45_na56me_45'
    print [sub(r'^(?P<pretext>.*_)(?P<number>\d+)$', lambda x : '%s%d' % (x.group('pretext'), int(x.group('number')) + 1), s) for s in (string2, string3, string4)]
    

    和输出:

    ['suppose_name_2', 'suppose_name_23', 'supp22ose45_na56me_46']
    

    更容易阅读的版本是这样的:

    from re import sub
    
    string2  = 'suppose_name_1'
    string3  = 'suppose_name_22'
    string4  = 'supp22ose45_na56me_45'
    regex = r'^(?P<pretext>.*_)(?P<number>\d+)$'
    
    def increment(matchObject):
        return '%s%d' % (matchObject.group('pretext'), int(matchObject.group('number')) + 1)
    
    for s in (string2, string3, string4):
        print sub(regex, increment, s)
    

    和输出:

    suppose_name_2
    suppose_name_23
    supp22ose45_na56me_46
    

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 2016-05-06
      • 2015-02-07
      • 2010-12-19
      相关资源
      最近更新 更多