編寫一個 Python 程序,使用 For 循環、while 循環刪除字符串中的字符的第一次出現,並通過一個示例運行。
刪除字符串中字符的第一次出現的 Python 程序示例 1
這個 python 程序允許用戶輸入字符串和字符。接下來,它使用 For 循環查找並刪除給定字符串中該字符的第一次出現。
首先,我們使用 For 循環來迭代字符串中的每個字符。在 For 循環中,我們使用 If 語句來檢查字符是否等於 ch。如果為真,則使用字符串切片索引刪除該字符,並使用 Break 語句退出循環。請參考弦文章了解蟒弦的一切
# Python Program to Remove the First Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
string2 = ''
length = len(string)
for i in range(length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
print("Original String : ", string)
print("Final String : ", string2)
刪除字符串中字符的第一次出現的 Python 程序示例 2
這個 python 代碼刪除一個字符的第一次出現與上面相同。然而,我們只是將 For 循環替換為 While 循環。
# Python Program to Remove First Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
string2 = ''
length = len(string)
i = 0
while(i < length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
i = i + 1
print("Original String : ", string)
print("Final String : ", string2)
Python 刪除字符串輸出中出現的字符的第一次出現
Please enter your own String : python programs
Please enter your own Character : p
Original String : python programs
Final String : ython programs
刪除字符串第一次出現的 Python 程序示例 3
刪除字符串第一次出現的 Python 代碼與第一個示例相同。但是,這次我們用 Python 函數來分離邏輯。
# Python Program to Remove First Occurrence of a Character in a String
def removeFirstOccur(string, char):
string2 = ''
length = len(string)
for i in range(length):
if(string[i] == char):
string2 = string[0:i] + string[i + 1:length]
break
return string2
str1 = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
print("Original String : ", str1)
print("Final String : ", removeFirstOccur(str1, char))
Python 刪除字符串輸出中出現的字符的第一次出現
Please enter your own String : tutorialgateway
Please enter your own Character : t
Original String : tutorialgateway
Final String : utorialgateway
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/269992.html