[英]Remove certain characters if they are not in a specific location in a string #python
我试图从我的 python class 中找出以下 function 情况。 我已经获得了删除这三个字母的代码,但正是从他们不希望我删除的地方。 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'))
检查这个:
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","")
我看到的其他回复不适用于文本中有多个“WGU”且开头有一个的前卫案例,例如
print(removeWGU("WGU, something else, another WGU..."))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.