English 中文(简体)
能够检测字符串中的int s,Python
原标题:Being able to detect int s in strings, Python

我正试图用python把一个数字和一个字符串分开。基本上我想要它,所以如果颜色==灰色+一个数字,那么它会返回那个数字。例如,如果颜色等于灰度23,则返回23。如果颜色等于灰色,则会触发else语句。

伪代码:

# = an int

def func (color):
    if color ==  gray  and a # :
        return int(#)
    else:
        print  pass 
最佳回答
if color.startswith("grey") and color[4:].isdigit():
    return int(color[4:])
else:
    return  pass 

color[4:]可以用比硬编码值4更通用的东西来代替,但由于“灰色”(或“灰色”-两者都用)是硬编码的,所以这似乎没有问题。

问题回答
import re

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

您可以使用正则表达式用于:

import re

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

未经测试,因此可能包含错误,但这是基本要点。





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签