Python replace函数怎么用
在Python中,字符串是不可变对象,即创建后无法更改。但是我们可以通过一些方法来修改字符串,其中之一就是使用 replace()
函数。replace()
函数可以用来替换字符串中的子串。
基本语法
replace()
函数的基本语法如下:
new_string = old_string.replace(old_substring, new_substring, count)
old_string
是原始字符串;old_substring
是要被替换的子字符串;new_substring
是用来替换的新字符串;count
是可选参数,表示替换的次数。如果不指定count
参数,则替换所有匹配的子字符串。
示例
让我们通过一个示例来演示 replace()
函数的用法:
string = "Hello, world! Hello, Python!"
new_string = string.replace("Hello", "Hi")
print(new_string)
运行结果:
Hi, world! Hi, Python!
在上面的示例中,我们将字符串 string
中的所有 “Hello” 替换为 “Hi”。
替换指定次数
如果我们只想替换指定次数的子字符串,可以将 count
参数设置为替换的次数。例如:
string = "apple, apple, apple, banana"
new_string = string.replace("apple", "orange", 2)
print(new_string)
运行结果:
orange, orange, apple, banana
上面的示例中,我们只替换了前两个 “apple”,而第三个 “apple” 没有被替换。
不改变原始字符串
需要注意的是,replace()
函数并不会改变原始字符串,而是返回一个新的字符串。原始字符串不会被修改。例如:
string = "I like apples"
new_string = string.replace("apples", "oranges")
print(string)
print(new_string)
运行结果:
I like apples
I like oranges
在上面的示例中,string
字符串保持不变,而 new_string
是替换后的新字符串。
区分大小写
replace()
函数是区分大小写的。也就是说,大写字母和小写字母被视为不同的字符。例如:
string = "Hello, World! hello, world!"
new_string = string.replace("hello", "Hi")
print(new_string)
运行结果:
Hello, World! Hi, world!
在上面的示例中,由于 “hello” 和 “Hello” 不是同一个字符串,只有第一个 “hello” 被替换为 “Hi”。
总结
通过本文的介绍,我们学习了如何使用 replace()
函数来替换字符串中的子串。我们可以指定要替换的子字符串,也可以指定替换的次数。需要注意的是 replace()
函数并不会改变原始字符串,而是返回一个新的字符串。此外,replace()
函数是区分大小写的。