How to make case sensitive string in Python?

I am trying to write code that compares two strings and returns a string if a match is found with a case-sensitive condition, with the exception of capital. That function that I wrote, and I found out that == is pretty good for comparing the case sensitively. However, it still prints January for the last test line, which is not expected. So can you help me?

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def valid_month(month): for x in months: if x==month.capitalize() : print x 

Test Codes:

  valid_month("january") valid_month("January") valid_month("foo") valid_month("") valid_month("jaNuary") 
+4
source share
3 answers

How about this:

 def valid_month(month): for x in months: if x[1:] == month[1:] and x[0].capitalize() == month[0].capitalize(): print x 

This will check the case with case sensitivity - except for the first character.

+5
source

because "janUAry".capitalize() is equal to "January"

 In [4]: "January"=="janUAry".capitalize() Out[4]: True 

The best version of your code might be:

 def valid_month(month): if month and month[0].capitalize()+month[1:] in months: print(month) else: print(month,"is not found") 

output:

 >>> valid_month("january") january >>> valid_month("January") January >>> valid_month("foo") foo is not found >>> valid_month("") is not found >>> valid_month("jaNuary") jaNuary is not found 
+3
source

capitalize converts your string to lowercase, but for the first letter, which becomes uppercase. So, "jaNuary".capitalize() becomes "January" , and your test is correct.

Obviously, this is the wrong approach. You can check if any letter except the first is uppercase:

 any(t.isupper() for t in month[1:]) 

and not executed if this case.

+2
source

Source: https://habr.com/ru/post/1433476/


All Articles