用替换函数和 For 循环编写一个 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)
在这个程序中,我们使用 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 替换字符串字符的代码与上面的例子相同。然而,我们使用的是对象循环。
# 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
标签: python基础