python - 仅替换字符串的结尾

标签 python string list

令我恼火的是不能在一行中执行以下操作。我觉得它可以通过列表推导来完成,但是怎么做呢?

given_string = "first.second.third.None"
string_splitted = given_string.split('.')
string_splitted[-1] = "fourth"
given_string = ".".join(string_splitted)

请注意,given_string 中点 (.) 的数量是常量 (3)。所以我一直想替换字符串的第四个片段。

最佳答案

看起来你应该能够在不拆分成数组的情况下做到这一点。找到最后一个 . 并切到那里:

> given_string = "first.second.third.None"
> given_string[:given_string.rfind('.')] + '.fourth'

'first.second.third.fourth'

关于python - 仅替换字符串的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53731198/

相关文章:

python - Tensorflow.js Layers 模型和 Graph 模型有什么区别?

php - 合并两个正则表达式以截断字符串中的单词

python - 在python中以所需格式排列列表的字符串

python - 如何对依赖于先前元素的列表元素执行操作?

javascript - 使用此代码在 JS 中查找字符串中最长的单词?

python - 将列表转换为集合和联合操作

python - Pymodbus 服务器写入回调

python - Pandas 应用一个函数将列表返回到更多列

python - 在 Python 中将表/数据框与公共(public)列连接起来

arrays - 将逗号分隔的字符串拆分为 shell 脚本中的数组值?