Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list and string matching

Tags:

python

match

I have following:

temp = "aaaab123xyz@+"

lists = ["abc", "123.35", "xyz", "AND+"]

for list in lists
  if re.match(list, temp, re.I):
    print "The %s is within %s." % (list,temp)

The re.match is only match the beginning of the string, How to I match substring in between too.

like image 774
pete Avatar asked Apr 23 '10 07:04

pete


People also ask

How do you match a string to a list in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do you match items in a list in Python?

Python set() method and == operator to compare two lists Further, the == operator is used for comparison of the data items of the list in an element-wise fashion.

How do you check if a list contains a particular string in Python?

The any() function is used to check the existence of an element in the list. it's like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list. Example: Python3.

Can Python lists work with strings?

Lists are one of the most common data structures in Python, and they are often used to hold strings.


2 Answers

You can use re.search instead of re.match.

It also seems like you don't really need regular expressions here. Your regular expression 123.35 probably doesn't do what you expect because the dot matches anything.

If this is the case then you can do simple string containment using x in s.

like image 136
Mark Byers Avatar answered Oct 24 '22 18:10

Mark Byers


Use re.search or just use in if l in temp:

Note: built-in type list should not be shadowed, so for l in lists: is better

like image 38
YOU Avatar answered Oct 24 '22 16:10

YOU