简体   繁体   English

如果某些字符不在字符串中的特定位置,则删除它们#python

[英]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.我试图从我的 python class 中找出以下 function 情况。 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. IE 从应该保留的第一行中删除 WGU,而不是从 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我看到的其他回复不适用于文本中有多个“WGU”且开头有一个的前卫案例,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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