简体   繁体   中英

Python convert a string to lowercase except some special strings

I'd like to convert a string to lowercase but if this string contains one of the special words it should leave as is.

specialwords = ['Special1', 'Special']

Let's say our input string is like this:

Ali is really Special.

Output should be like this:

ali is really Special

Here is the code I've used so far.

def makeUrl(inputString):
    list =  {"ı": "i",
             "I": "ı",
             "İ": "İ",
             "î": "i",
             "Ç": "c",
             "ç": "c",
             " ": "-",
             "ş": "s",
             "Ş": "s",
             "Ğ": "g",
             "ğ": "g",
             "Ü": "u",
             "ü": "u",
             "Ö": "o",
             "ö": "o",
             "!": "",
             "?": "",
             "'": "",
             "“": "",
             "”": "",
             "â": "a"}

    inputString = inputString.encode('utf8', 'replace')

    for letter in list:
        inputString = inputString.replace(letter, liste[letter])
    if "Ali" in inputString:
        return inputString
    else:
        return inputString.lower()
specialwords = ['Special1', 'Special']
string = "Ali is really Special"

toLower = lambda x: " ".join( a if a in specialwords else a.lower()
            for a in x.split() )

print (toLower(string))
# ali is really Special

In case of any punctuations in the string , you can easily strip them off with a simple lambda :

from string import punctuation
p_strip = lambda x: "".join(w for w in x if w not in punctuation)

string = "Ali is really Special."

# Now `toLower` function should look something like this:
toLower = lambda x: " ".join( a if p_strip(a) in specialwords else a.lower()
    for a in x.split() )

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