Python 的 str.replace(~) 方法返回字符串的新副本,其中所有出現的 old 子字符串都替換為 new 子字符串。
參數
1. old | string
要替換為 new 的子字符串。
2. new | string
用於替換 old 子字符串的子字符串。
3. count | number | optional
要替換的 old 子字符串出現的次數。默認為所有出現的情況。
返回值
返回字符串的新副本,其中所有出現的 old 子字符串均替換為 new 子字符串。
如果提供了 count 參數,則僅替換第一個出現的 count。
例子
基本用法
要將所有出現的 "Hi" 替換為 "Hello" :
x = "Hi Hi Hi!"
x.replace('Hi', 'Hello')
'Hello Hello Hello!'
我們可以看到,在返回的字符串中,所有出現的 'Hi' 都被替換為 'Hello'。
計數參數
僅替換前兩次出現的 'Hi' :
y = "Hi Hi Hi!"
y.replace('Hi', 'Hello', 2)
'Hello Hello Hi!'
我們可以看到,在返回的字符串中,隻有前兩次出現的 'Hi' 被替換為 'Hello'。
相關用法
- Python String replace()用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
- Python String rindex()用法及代碼示例
- Python String rjust()用法及代碼示例
- Python String rindex方法用法及代碼示例
- Python String rstrip()用法及代碼示例
- Python String rfind方法用法及代碼示例
- Python String rsplit方法用法及代碼示例
- Python String rfind()用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String startswith()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | replace method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
