共計 698 個字符,預計需要花費 2 分鐘才能閱讀完成。
要交換字符串中的兩個子串,可以使用 replace() 函數來實現。具體步驟如下:
- 首先找到要交換的兩個子串在原字符串中的起始位置。
- 使用 replace() 函數將第一個子串替換成一個臨時的占位符,例如 "TEMP"。
- 將第二個子串替換成第一個子串。
- 將臨時的占位符替換成第二個子串。
以下是一個示例代碼:
def swap_substrings(input_string, substr1, substr2):
# 找到兩個子串在原字符串中的起始位置
index1 = input_string.find(substr1)
index2 = input_string.find(substr2)
# 使用 replace() 函數進行交換
temp_string = input_string.replace(substr1, "TEMP")
temp_string = temp_string.replace(substr2, substr1)
output_string = temp_string.replace("TEMP", substr2)
return output_string
input_string = "hello world"
substr1 = "hello"
substr2 = "world"
output_string = swap_substrings(input_string, substr1, substr2)
print(output_string)
在上面的示例中,我們定義了一個 swap_substrings 函數來實現字符串中兩個子串的交換。然后我們將 "hello" 和 "world" 交換,并輸出結果 "world hello"。
丸趣 TV 網 – 提供最優質的資源集合!
正文完