简体   繁体   中英

TypeError: can only concatenate str (not “NoneType”) to str

Trying to build an uppercase to lowercase string converter in Python 3.7, this is my code:

def convertChar(char):
    if char >= 'A' and char <= 'Z':
        return chr(ord(char) + 32)
def toLowerCase(string):
    for char in string:
        string = string + convertChar(char)
    return string
string = input("Enter string - ")
result = toLowerCase(string)
print(result)

And this is my output:

Enter string - HELlo
Traceback (most recent call last):
  File "loweralph.py", line 11, in <module>
    string = toLowerCase(result)
  File "loweralph.py", line 6, in toLowerCase
    result = result + convertChar(char)
TypeError: can only concatenate str (not "NoneType") to str

I am really new to Python and I saw answers for 'list to list' TypeErrors and one other answer for str to str, but I couldn't relate it to my code. If somebody could explain what I'm doing wrong, it would be great!

You need to add some exception cases to your code. Firstly, what if the entered character is already lower case?

You can do something of this sort:

def convertChar(char):
    if char >= 'A' and char <= 'Z':
        return chr(ord(char) + 32)

    return char

This might not be the most ideal solution, but it will take care of most of the things. That is, only if the entered character is upper case, it is converted to lower case. For all other cases (whether it is a lower case character, a number et cetra), the character is returned as it is.

Secondly, if you are making a upper case to lower case converter, output of HElLo should be hello , not HElLohello .

For this, you need to modify your second function as follows:

def toLowerCase(string):
    newString = []
    for char in string:
        newString.append(convertChar(char))
    return ''.join(newString)

Finally, you might want to consider using .upper() in-built function.

Example of usage:

'HeLlo'.upper()

As coldspeed has commented, when you pass lower case letter to convertChar, the function won't return a proper character. Hence the error.

Also, with 'string = string + convertChar(char)' you are appending to the same input string. This is wrong. You need to use a new empty string for that.

I don't know the reason for building your own method, but you could use the built-in lower() method instead. For example:

my_string = input("Enter string - ")
result = my_string.lower()
print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM