用替換函數和 For 循環編寫一個 Python 程序來替換字符串中的字符。
替換字符串 1 中字符的 Python 程序
該程序允許用戶輸入字符串、要替換的字符和要替換的新字符。接下來,我們使用一個名為 replace 的內置字符串函數,用一個新字符替換用戶給定的字符。
# Python program to Replace Characters in a String
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = str1.replace(ch, newch)
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
替換字符串的程序示例 2
在這個程序中,我們使用 For 循環來迭代字符串中的每個字符。在 For 循環中,我們使用 If 語句來檢查字符串字符是否等於 ch。如果為真, Python 替換為 Newch
# Python program to Replace Characters in a String
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = ''
for i in range(len(str1)):
if(str1[i] == ch):
str2 = str2 + newch
else:
str2 = str2 + str1[i]
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
Python 替換字符串輸出
Please Enter your Own String : tutorial gateway team
Please Enter your Own Character : t
Please Enter the New Character : P
Original String : tutorial gateway team
Modified String : PuPorial gaPeway Peam
Python 替換字符串中的字符示例 3
這個 Python 替換字符串字符的代碼與上面的例子相同。然而,我們使用的是對象循環。
# Python program to Replace Characters in a String
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = ''
for i in str1:
if(i == ch):
str2 = str2 + newch
else:
str2 = str2 + i
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
Python 替換字符串輸出
Please Enter your Own String : python programming examples
Please Enter your Own Character : o
Please Enter the New Character : G
Original String : python programming examples
Modified String : pythGn prGgramming examples
原創文章,作者:ADZSW,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127787.html