I need to match the following string File system full
. The problem is Starting F can be lowercase or capital. How can I do this in Python when string comparisons are usually case-sensitive?

- 40,133
- 25
- 115
- 157

- 465
- 1
- 6
- 12
-
2Possible duplicate: [How do I do a case insensitive string comparison in Python?](http://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison-in-python) – Kim Hansson Jan 22 '13 at 10:25
-
What do you mean by "match"? Is there any `if` condition? – georg Jan 22 '13 at 11:08
-
Hmm, why is it still open when there had been several questions like this before? – László Papp Oct 16 '13 at 13:36
9 Answers
I'll be providing boolean indicators for you to play around with (rather than actual if
blocks for the sake of conciseness.
Using Regex:
import re
bool(re.match('[F|f]',<your string>)) #if it matched, then it's true. Else, false.
if the string could be anywhere in your output (I assume string)
import re
bool(re.search('[F|f]ile system full',<your string>))
Other options:
checking for 'f' and 'F'
<your string>[0] in ('f','F')
<your string>.startswith('f') or <your string>.startswith('F')
And there's the previously suggested lower
method:
<your string>.lower() == 'f'

- 8,747
- 4
- 40
- 60
test_string = "File system full"
if "file system full" == test_string.lower():
# do stuff

- 24,192
- 9
- 66
- 88
>>> s = 'ABC'
>>> s.lower()
'abc'
>>>
After you could use any pattern for matching.

- 8,370
- 4
- 37
- 60
Try converting string into any common(lower or upper) case and then compare

- 23,144
- 56
- 154
- 243
You can try like this,
>>> import re
>>> bool(re.match('File system full','file system full', re.IGNORECASE))
True
For the more information, re.IGNORECASE

- 20,457
- 4
- 34
- 42
You can use this function
Here,
Both the strings are converted to lowercase using str.lower()
,
If the first letter is the same in both strings, it returns True
otherwise False
def match1(str1 ,str2):
str1 = str1.lower() # to ignore the case
str2 = str2.lower()
if str1[0] == str2[0]:
return True
return False
Run on IDLE
>>> mystr = 'File system full'
>>> test1 = 'Flow'
>>> test2 = 'flower'
>>> match1(mystr,test1)
True
>>> match(mystr,test2)
True
I won't recommend using this technique as
You would need to have both lower and upper-case of the input string's letters
but it works :)
def match2(str1 ,str2):
if str2[0] == str1[0].lower()\
or str2[0] == str1[0].upper():
return True
return False

- 18,287
- 11
- 43
- 96
You can also do in the below way:
st="File system full"
vl = re.search(r"(?i)File system full", st)
(?i)
matches both uppercase and lower case letters.
-
@Sandeep Krishnan You can also implement in the way which i have added. when you get a chance please have a look. – Fla-Hyd Feb 25 '13 at 15:53