I want to search a string in each line of a list, it will match every case of UP/LOW combination possible
For example: If i type in "all" and it will search "all" "All "ALL" "aLL" "aLl" ... etc. It works like advanced search in text document i think.
More detail : if 'all'
was input, then any of these strings appear in that line will return FOUNDED : 'all', 'alL', 'All', 'ALL', 'aLL', 'aLl', 'AlL', 'ALl'
Here is how i done with correct string find
string = "all"
line[i].find(string)
if the line
was "ALL" , the result was not found
, so this is a limitation.
>>> lines = ['All', 'ALL', 'all', 'WALL', 'BLAA', 'Balls']
>>> for line in lines:
... if 'all' in line.lower():
... print(line)
All
ALL
all
WALL
Balls
Try with list comprehension,
In [25]: line = ['All', 'ALL', 'all', 'WALL', 'BLAA', 'Balls']
In [26]: [i for i in line if 'all' in i.lower() ]
Out[26]: ['All', 'ALL', 'all', 'WALL', 'Balls']
There are a few ways of achieving that. Here they are:
1. Changing the case of the string you are searching into:
line[i].lower().find(string.lower())
or
line[i].upper().find(string.upper())
Here we're abusing of the immutability of the original strings, since they won't be changed although we apply .upper()
to them, since we're not doing any assignment.
2. using the re
module would also be helpful:
import re
re.search('all', line[0], re.IGNORECASE)
or
re.search('(?i)all',line[0])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.