Home > Back-end >  Why Python returns True for empty space as upper()?
Why Python returns True for empty space as upper()?

Time:01-16

Anyone can clarify why the below program returns "J F K" with spaces and not "JFK" ?

string = "John Fitzgerald Kennedy"
initials = ""
for letter in string:
    if letter == letter.upper():
        initials  = letter
print(initials)

On the other hand , the below program returns "JFK" without spaces ,

string = "John Fitzgerald Kennedy"
initials = ""
for letter in string:
    if letter != letter.lower():
        initials  = letter
print(initials)

Thanks!!!

EDIT : Ah ... Do I feel really silly for asking this after reading the answers. I should have tried out the below before asking ... It returns "ohn itzgerald ennedy"

string = "John Fitzgerald Kennedy"
initials = ""
for letter in string:
    if letter == letter.lower():
        initials  = letter
print(initials)

Thanks everyone :)

CodePudding user response:

Try out string.upper(). You'll get 'JOHN FITZGERALD KENNEDY'. Notice that the uppercase version of a space is unchanged.

If you want to check if a character is upper case, you can use isupper:

string = "John Fitzgerald Kennedy"
initials = ""
for letter in string:
    if letter.isupper():
        initials  = letter
print(initials)

CodePudding user response:

Because

space(" ") == space(" ").upper() --> True

Also

space(" ") != space(" ").upper() --> False

  •  Tags:  
  • Related