python-3.x - 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
解决方案
这是预期的行为。看看参数的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'
推荐阅读
- scala - Spark Dataframe 的 where 子句可以将变量作为参数吗?
- java - 如何将可绘制对象分配给小部件按钮
- multithreading - C# - WebDriver - MSTest 框架并行执行
- r - 在 R Shiny 中为进度条使用并行 foreach
- java - PDFBox:PDDocument 和 PDPage 是否相互引用?
- powershell - 为什么 PowerShell 在“Get-Credentials”上意外退出?
- node.js - Mongoose find() 回调实际上没有被调用
- c# - 在同一个“使用”中连接到不同的连接字符串
- json - Android Kotlin 解析嵌套 JSON
- asp.net - 无法加载文件或程序集 'msshrtmi, Version=2.7.0.0 - 什么 SDK 安装它?