Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a case sensitive string compare in Python?

Tags:

python

string

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

  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")
like image 862
Figen Güngör Avatar asked Dec 27 '22 18:12

Figen Güngör


1 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 test equality with case sensitivity - except for the first character.

like image 61
arshajii Avatar answered Dec 29 '22 08:12

arshajii