首页 新闻 会员 周边 捐助

line.replace()如果没有替换的内容,返回什么

0
[已关闭问题] 关闭于 2025-12-06 21:53

当要替换的内容不存在时, line.replace()  会返回原字符串的副本(内容相同的新字符串对象)。

s = "hello world"

# 1. 要替换的内容存在
result1 = s.replace("world", "python")
print(result1) # 'hello python'

# 2. 要替换的内容不存在
result2 = s.replace("java", "python")
print(result2) # 'hello world' ← 原样返回
print(result2 == s) # True (内容相同)
print(result2 is s) # False (不是同一个对象)

# 3. 原字符串不变
print(s) # 'hello world'

*Tesla*的主页 *Tesla* | 小虾三级 | 园豆:1258
提问于:2025-12-06 21:53
< >
分享
所有回答(1)
0

记住:字符串是不可变类型, replace()  总是返回新对象,即使什么都没替换。

*Tesla* | 园豆:1258 (小虾三级) | 2025-12-06 21:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册