寫一個 Python 程序,用替換函數用字符串中的連字符替換空格,用一個實際例子替換 For 循環。
用連字符替換字符串中空格的 Python 程序示例 1
這個 python 程序允許用戶輸入一個字符串。接下來,我們使用內置的替換字符串函數用連字符替換空白。
# Python program to Replace Blank Space with Hyphen in a String
str1 = input("Please Enter your Own String : ")
str2 = str1.replace(' ', '_')
print("Original String : ", str1)
print("Modified String : ", str2)
Python 用連字符輸出替換字符串中的空格
Please Enter your Own String : Hello World Program
Original String : Hello World Program
Modified String : Hello_World_Program
用連字符替換字符串中空格的 Python 程序示例 2
在這個程序中,我們使用 For 循環來迭代字符串中的每個字符。在 For 循環中,我們使用 If 語句來檢查字符串字符是空的還是空格。如果是真的, Python 會用 _。
# Python program to Replace Blank Space with Hyphen in a String
str1 = input("Please Enter your Own String : ")
str2 = ''
for i in range(len(str1)):
if(str1[i] == ' '):
str2 = str2 + '_'
else:
str2 = str2 + str1[i]
print("Modified String : ", str2)
Python 用連字符輸出替換字符串中的空格
Please Enter your Own String : Hello World!
Modified String : Hello_World!
>>>
Please Enter your Own String : Python program Output
Modified String : Python_program_Output
用連字符替換字符串中空格的 Python 程序示例 3
這個 Python 用連字符替換空格的程序與上面的例子相同。然而,我們使用的是對象循環。
# Python program to Replace Blank Space with Hyphen in a String
str1 = input("Please Enter your Own String : ")
str2 = ''
for i in str1:
if(i == ' '):
str2 = str2 + '_'
else:
str2 = str2 + i
print("Modified String : ", str2)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/254825.html