首页 > 解决方案 > python中的字符串替换是替换整个字符串

问题描述

当我进行字符串替换时,出现错误。例如:我的字符串是my_string = '15:15'. 我想将15冒号后面的内容替换为30. 例如我需要'15:30'. 当我尝试进行字符串替换时,它对于所有其他值都可以正常工作,例如'09:15', '09:20'

我努力了:

my_string = '15:15'
my_new_string = my_string.replace(my_string[-2:], '30')

my_string = '15:15'
my_new_string = my_string.replace(my_string[-2:], '30')

我期待的是15:30,但我的实际输出是30:30

标签: python-3.xstring

解决方案


这是预期的行为。看看参数的str.replace()含义是什么:

replace(...)
    S.replace(old, new[, count]) -> string

    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.

它不会替换子字符串,而是替换所有作为第一个参数传递的内容。

通过调用my_string.replace(my_string[-2:], '30'),您实际上是在调用'15:15'.replace('15', '30')- 它将所有出现的“15”替换为“30”,所以你最终会得到'30:30'.

如果要替换最后两个字符,请颠倒逻辑:将所有内容保留到最后两个字符,然后在末尾添加所需的 '30' 字符串:

my_new_string = my_string[:-2] + '30'

推荐阅读