简体   繁体   中英

Remove certain characters if they are not in a specific location in a string #python

I am trying to figure out the following function situation from my python class. I've gotten the code to remove the three letters but from exactly where they don't want me to. IE removing WGU from the first line where it's supposed to stay but not from WGUJohn.

# Complete the function to remove the word WGU from the given string
# ONLY if it's not the first word and return the new string
def removeWGU(mystring):
    #if mystring[0]!= ('WGU'):
        #return mystring.strip('WGU')
    #if mystring([0]!= 'WGU')
        #return mystring.split('WGU')
    
# Student code goes here
    
# expected output: WGU Rocks
print(removeWGU('WGU Rocks'))
    
# expected output: Hello, John
print(removeWGU('Hello, WGUJohn'))

Check this one:

def removeWGU(mystring):
    s = mystring.split()
    if s[0] == "WGU":
        return mystring
    else:
        return mystring.replace("WGU","")
print(removeWGU('WGU Rocks'))
print(removeWGU('Hello, WGUJohn'))
def removeWGU(mystring):
    return mystring[0] + mystring[1:].replace("WGU","")

Other responses I seen wouldn't work on a edgy case where there is multiple "WGU" in the text and one at the beginning, such as

print(removeWGU("WGU, something else, another WGU..."))

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