Python:将字符串变量与多个子字符串进行比较

时间:2013-10-29 00:18:20

标签: python

我是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 个答案:

答案 0 :(得分: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
>>> 

答案 1 :(得分: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

答案 2 :(得分: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!" #

答案 3 :(得分: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"

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