[英]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.