python3.6 str.replace() 字符串替换方法

python3.6 str.replace() 字符串替换方法

源码

    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
        
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

全部替换

str = "1,22,3,1,1,1,4,22,22"
print(str.replace("1", "8"))

把字符串的全部 1 替换成 8

结果

8,22,3,8,8,8,4,22,22

限定替换次数

str = "1,22,3,1,1,1,4,22,22"

print(str.replace("1", "8", 2))
print(str.replace("22", "99", 2))

第3个参数是替换的字符串开始,替换最大次数

结果

8,22,3,8,1,1,4,22,22
1,99,3,1,1,1,4,99,22

猜你喜欢

转载自blog.csdn.net/qq_38463737/article/details/112652553