用一個實例編寫一個 Python 程序來刪除字元串中的奇數字元。
去除字元串中奇數字元的 Python 程序示例 1
這個 python 程序允許用戶輸入一個字元串。首先,我們使用 For 循環來迭代字元串中的每個字元。在 For 循環中,我們使用 If 語句來檢查索引值是否可以被真整除。如果為真,則將字元(索引位置–1)添加到字元串 2 中。
# Python program to Remove Odd Characters in a String
str1 = input("Please Enter your Own String : ")
str2 = ''
for i in range(1, len(str1) + 1):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]
print("Original String : ", str1)
print("Final String : ", str2)
Python 使用 for 循環輸出移除字元串中的奇數字元
Please Enter your Own String : Tutorial Gateway
Original String : Tutorial Gateway
Final String : uoilGtwy
刪除字元串中奇數字元的 Python 程序示例 2
本程序程序去除奇數字元同上。然而,我們只是將 Python 代碼中的 For Loop 替換為 While Loop 。
# Python program to Remove Odd Characters in a String
str1 = input("Please Enter your Own String : ")
str2 = ''
i = 1
while(i <= len(str1)):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]
i = i + 1
print("Original String : ", str1)
print("Final String : ", str2)
Python 使用 while 循環輸出移除字元串中的奇數字元
Please Enter your Own String : Python Programs
Original String : Python Programs
Final String : yhnPorm
刪除字元串中奇數字元的 Python 程序示例 3
這個 Python 去除奇數字元的程序與第一個例子相同。但是,這次我們用 Python 函數來分離邏輯。
# Python program to Remove Odd Characters in a String
def RemoveOddCharString(str1):
str2 = ''
for i in range(1, len(str1) + 1):
if(i % 2 == 0):
str2 = str2 + str1[i - 1]
return str2
string = input("Please Enter your Own String : ")
print("Original String : ", string)
print("Final String : ", RemoveOddCharString(string))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/271102.html