1

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.

Federal Reserve
  • 121
  • 1
  • 7
  • 2
    can you just lowercase `line[i]`? and see if `all` is there? – depperm Apr 18 '17 at 13:45
  • 1
    Possible duplicate of [Case insensitive Python regular expression without re.compile](http://stackoverflow.com/questions/500864/case-insensitive-python-regular-expression-without-re-compile) – Peter Wood Apr 18 '17 at 13:47
  • @depperm Yes it'd be done but I must keep the integrity of data so anyway else – Federal Reserve Apr 18 '17 at 13:50
  • you could create a copy and lowercase the copy and check.... – depperm Apr 18 '17 at 13:56
  • You can convert the line and the search to the same case: `line[i].lower().find(string.lower())`. It doesn't change the original strings as they are immutable. – Peter Wood Apr 18 '17 at 14:03
  • Does this answer your question? [How to generate all combinations of lower and upper characters in a word?](https://stackoverflow.com/questions/50775110/how-to-generate-all-combinations-of-lower-and-upper-characters-in-a-word) – iacob Mar 11 '21 at 15:29

3 Answers3

2
>>> lines = ['All', 'ALL', 'all', 'WALL', 'BLAA', 'Balls']
>>> for line in lines:
...     if 'all' in line.lower():
...         print(line)


All
ALL
all
WALL
Balls
Al Sweigart
  • 11,566
  • 10
  • 64
  • 92
A.N.
  • 278
  • 2
  • 13
1

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']
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
1

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])
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44