Reputation: 795
I am new to Python and trying to learn python from Perl. In Perl, if I want to compare a string against multiple sub-strings, I would use the following:
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
How can I do this in python?
Upvotes: 1
Views: 159
Reputation: 304147
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
Upvotes: 2
Reputation: 512
Python has regular expressions. So you could do this:
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"
Normally I would tell you to avoid regular expressions if you can. But matching one of multiple sub-strings is actually a case where they likely perform better than a loop. This is especially true as the number of sub-strings grows.
Upvotes: 0
Reputation: 2896
With regular expressions:
import re
city = re.compile('kyo|par|omba', re.I)
matchCity = lambda x: city.search(x)
And you can use matchCity("example_city")
as condition:
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!" #
Upvotes: 0
Reputation: 129507
You don't actually need regex for this:
>>> 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
>>>
Upvotes: 3