开发者

Being able to detect int's in strings, Python

开发者 https://www.devze.com 2023-02-08 18:42 出处:网络
I\'m trying to seperate a number from a string in python. Basically I want it so if color == \'gray\' + a number, then it will return that number. For example if color equaled \'grey23\', it would ret

I'm trying to seperate a number from a string in python. Basically I want it so if color == 'gray' + a number, then it will return that number. For example if color equaled 'grey23', it would return 23. If color eq开发者_运维百科ualed 'grey', it would trigger the else statement.

pseudo code:

# = an int

def func (color):
    if color == 'gray' and a # :
        return int(#)
    else:
        print 'pass'


import re

def func (color):
    try:
        return int(re.search('(\d+)$',color).group(0)))
    except AttributeError:
        print 'pass'


You can use regular expressions for that:

import re

matches = re.match('\w+(\d+)', color)
result = matches.groups()
if(len(result) > 0):
    return result[0]
else:
    return 'pass'

Not tested, so it could contain errors, but this is the basic gist.


if color.startswith("grey") and color[4:].isdigit():
    return int(color[4:])
else:
    return 'pass'

color[4:] could be replaced by something more generic han the hardcoded value 4, but as "grey" (or "gray" - you use both) is hardcoded there seemed no problem with this.

0

精彩评论

暂无评论...
验证码 换一张
取 消