1

我是 Python 新手,正在尝试从 Perl 学习 Python。在 Perl 中,如果我想将一个字符串与多个子字符串进行比较,我会使用以下内容:

sub matchCity {
    my $cityName = shift;
    print "$cityName is a valid city name\n" if ($cityName =~ /kyo|par|omba/);
}

matchCity('tokyo'); # tokyo is a valid city name
matchCity('paris'); # paris is a valid city name
matchCity('bombay'); # bombay is a valid city name
matchCity('chicago'); # Doesn't print anything

我怎样才能在python中做到这一点?

4

4 回答 4

3

您实际上不需要正则表达式:

>>> def matchCity(s):
...     if any(r in s for r in ('kyo','par','omba')):
...         print s, 'is a valid city name'
... 
>>> matchCity('tokyo')
tokyo is a valid city name
>>> matchCity('paris')
paris is a valid city name
>>> matchCity('bombay')
bombay is a valid city name
>>> matchCity('chicago')  # doesn't print anything
>>> 
于 2013-10-29T00:23:30.403 回答
2
import re

def matchCity(city_name):
    if re.search('kyo|par|omba', city_name):
        print "{} is a valid city name".format(city_name)

matchCity('tokyo') # tokyo is a valid city name
matchCity('paris') # paris is a valid city name
matchCity('bombay') # bombay is a valid city name
matchCity('chicago') # Doesn't print anything
于 2013-10-29T00:22:49.407 回答
0

使用正则表达式:

import re
city = re.compile('kyo|par|omba', re.I)
matchCity = lambda x: city.search(x)

您可以matchCity("example_city")用作条件:

if matchCity("tokyo"):   print "Valid city!" # Valid city!
if matchCity("paris"):   print "Valid city!" # Valid city!
if matchCity("bombay"):  print "Valid city!" # Valid city!
if matchCity("chicago"): print "Valid city!" #
于 2013-10-29T00:29:12.630 回答
0

Python 有正则表达式。所以你可以这样做:

import re

city_names = re.compile(r'kyo|par|omba')

def match_city(city_name):
    if city_names.search(city_name):
        print city_name, "is a valid city name"

通常,如果可以,我会告诉您避免使用正则表达式。但是匹配多个子字符串中的一个实际上是它们可能比循环表现更好的情况。随着子字符串数量的增加,尤其如此。

于 2013-10-29T00:32:26.893 回答