如何替换字符串末尾的某些字符?

发布于 2024-09-18 18:16:15 字数 392 浏览 8 评论 0原文

我想替换 python 字符串末尾的字符。我有这个字符串:

s = "123123"

我想将最后一个 2 替换为 x。假设有一个名为 replace_last 的方法:

>>> replace_last(s, '2', 'x')
'1231x3'

是否有任何内置或简单的方法可以执行此操作?


它类似于 python 的 str.replace() :

>>> s.replace('2', 'x', 1)
'1x3123'

但它是从头到尾。

I want to replace characters at the end of a python string. I have this string:

s = "123123"

I want to replace the last 2 with x. Suppose there is a method called replace_last:

>>> replace_last(s, '2', 'x')
'1231x3'

Is there any built-in or easy method to do this?


It's similar to python's str.replace():

>>> s.replace('2', 'x', 1)
'1x3123'

But it's from the end to beginning.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

虚拟世界 2024-09-25 18:16:15

使用正则表达式函数 re.sub 替换字符串末尾的单词

import re
s = "123123"
s = re.sub('23

Prints:

1231penguins

import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s

Prints:

penguins3123
, 'penguins', s) print s

Prints:

Prints:

Using regular expression function re.sub to replace words at end of string

import re
s = "123123"
s = re.sub('23

Prints:

1231penguins

or

import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s

Prints:

penguins3123
, 'penguins', s) print s

Prints:

or

Prints:

筱武穆 2024-09-25 18:16:15

这正是 rpartition 函数用于:

S.rpartition(sep) -> (头、九、尾)

S末尾开始,在S中搜索分隔符sep,然后返回
它之前的部分、分隔符本身以及它之后的部分。如果
未找到分隔符,返回两个空字符串和S

我编写了这个函数,展示了如何在您的用例中使用 rpartition:

def replace_last(source_string, replace_what, replace_with):
    head, _sep, tail = source_string.rpartition(replace_what)
    return head + replace_with + tail

s = "123123"
r = replace_last(s, '2', 'x')
print r

输出:

1231x3

This is exactly what the rpartition function is used for:

S.rpartition(sep) -> (head, sep, tail)

Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.

I wrote this function showing how to use rpartition in your use case:

def replace_last(source_string, replace_what, replace_with):
    head, _sep, tail = source_string.rpartition(replace_what)
    return head + replace_with + tail

s = "123123"
r = replace_last(s, '2', 'x')
print r

Output:

1231x3
不回头走下去 2024-09-25 18:16:15

这是少数没有左右版本的字符串函数之一,但我们可以使用一些有左右版本的字符串函数来模拟行为。

>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'

或者

>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'

This is one of the few string functions that doesn't have a left and right version, but we can mimic the behaviour using some of the string functions that do.

>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'

or

>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
染年凉城似染瑾 2024-09-25 18:16:15
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'

对于你的第二个例子

>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'

For your second example

>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
情何以堪。 2024-09-25 18:16:15

当想要的匹配位于字符串末尾时, re.sub来救援。

>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb
, 'xxx', s)
'aaa bbb aaa xxx'
>>> 

When the wanted match is at the end of string, re.sub comes to the rescue.

>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb
, 'xxx', s)
'aaa bbb aaa xxx'
>>> 
霊感 2024-09-25 18:16:15

这是基于对您的问题的简单解释的解决方案。更好的答案需要更多信息。

>>> s = "aaa bbb aaa bbb"
>>> separator = " "
>>> parts = s.split(separator)
>>> separator.join(parts[:-1] + ["xxx"])
'aaa bbb aaa xxx'

更新

(看到编辑后的问题后)另一个非常具体的答案。

>>> s = "123123"
>>> separator = "2"
>>> parts = s.split(separator)
>>> separator.join(parts[:-1]) + "x" + parts[-1]
'1231x3'

更新2

有更好的这样做的方法。由 @mizipzor 提供。

Here is a solution based on a simplistic interpretation of your question. A better answer will require more information.

>>> s = "aaa bbb aaa bbb"
>>> separator = " "
>>> parts = s.split(separator)
>>> separator.join(parts[:-1] + ["xxx"])
'aaa bbb aaa xxx'

Update

(After seeing edited question) another very specific answer.

>>> s = "123123"
>>> separator = "2"
>>> parts = s.split(separator)
>>> separator.join(parts[:-1]) + "x" + parts[-1]
'1231x3'

Update 2

There is far better way to do this. Courtesy @mizipzor.

一花一树开 2024-09-25 18:16:15

有一种方法可以处理替换以使其向后工作。
这个想法是使用 [::-1] 反转字符串、要替换的文本和新文本。逻辑保持不变。

例如:

>>> a = "123 456 123 456 123 456"

我们想要用“abc”替换最后一次(或两次或n次)出现的“123”,

>>> a[::-1].replace("123"[::-1], "abc"[::-1], 1)[::-1]
'123 456 123 456 abc 456'

这可以作为一个行为与replace完全相同的函数。

def replace_right(text, old, new, count=-1):
    """
    Return a copy of text with all occurrences of substring old
    replaced by new, starting from the right.

    If count is given and is not -1, only the first count
    occurrences are replaced.
    """
    return text[::-1].replace(old[::-1], new[::-1], count)[::-1]

执行:

>>> replace_right(a, "123", "abc", 1)
'123 456 123 456 abc 456'

>>> replace_right(a, "123", "abc", 2)
'123 456 abc 456 abc 456'

There is a way to handle replace to make it work backwards.
The idea is to reverse the string, text to replace and new text using [::-1]. The logic stays the same.

For example:

>>> a = "123 456 123 456 123 456"

and we want to replace the last one, (or two, or n) occurrences of "123" with "abc"

>>> a[::-1].replace("123"[::-1], "abc"[::-1], 1)[::-1]
'123 456 123 456 abc 456'

This could be put as a function that behaves exactly like replace.

def replace_right(text, old, new, count=-1):
    """
    Return a copy of text with all occurrences of substring old
    replaced by new, starting from the right.

    If count is given and is not -1, only the first count
    occurrences are replaced.
    """
    return text[::-1].replace(old[::-1], new[::-1], count)[::-1]

Execution:

>>> replace_right(a, "123", "abc", 1)
'123 456 123 456 abc 456'

>>> replace_right(a, "123", "abc", 2)
'123 456 abc 456 abc 456'
拧巴小姐 2024-09-25 18:16:15

有一个非常简单的方法可以做到这一点,按照我的步骤

s = "stay am stay am  delete am"
#  want to remove the last am
s = s[:s.rfind('am')]
print(s)

首先,我们找到 am 最后一次出现的索引号,然后将第 0 个索引指向该特定索引。

There is a very easy way to do this, follow my steps

s = "stay am stay am  delete am"
#  want to remove the last am
s = s[:s.rfind('am')]
print(s)

Here at first, we find the index number of am's last occurrence, then take 0th index to that particular index.

我早已燃尽 2024-09-25 18:16:15

我得到了一个棘手的答案,但它不够高效

fname = '12345.png.pngasdfg.png'
suffix = '.png'
fname_rev = fname[::-1]
suffix_rev = suffix[::-1]
fullname_rev = fname_rev.replace(suffix_rev, '', 1)
fullname = fullname_rev[::-1]
fullname '12345.png.pngasdfg'

内置函数replace()需要三个参数
str.replace(旧的,新的,max_time)
所以你可以从原始字符串中删除最后一个匹配的字符串

I got a tricky answer, but it is not efficient enough

fname = '12345.png.pngasdfg.png'
suffix = '.png'
fname_rev = fname[::-1]
suffix_rev = suffix[::-1]
fullname_rev = fname_rev.replace(suffix_rev, '', 1)
fullname = fullname_rev[::-1]
fullname '12345.png.pngasdfg'

Built-in function replace() takes three arguments
str.replace(old, new, max_time)
So you can delete the last mached string from the origional string

戏舞 2024-09-25 18:16:15

完整的解决方案 str.rfind 和索引,处理不匹配的情况:

def str_rreplace(haystack, needle, replacement):
    pos = haystack.rfind(needle)
    if pos == -1:
        return haystack
    return haystack[:pos] + replacement + haystack[pos + len(needle):]

A complete solution with str.rfind and indexing, handling the no-matches case:

def str_rreplace(haystack, needle, replacement):
    pos = haystack.rfind(needle)
    if pos == -1:
        return haystack
    return haystack[:pos] + replacement + haystack[pos + len(needle):]
深爱成瘾 2024-09-25 18:16:15

对于第二个例子,我推荐rsplit,因为它使用起来非常简单,并且直接达到了目标。这是它的一个小功能:

def replace_ending(sentence, old, new):
    if sentence.endswith(old):
        i = sentence.rsplit(old,1)
        new_sentence =new.join(i)
        return new_sentence
    return sentence

print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx")) 

输出:

aaa bbb aaa xxx

For the second example, I would recommend rsplit, as it is very simple to use and and directly achieves the goal. Here is a little function with it:

def replace_ending(sentence, old, new):
    if sentence.endswith(old):
        i = sentence.rsplit(old,1)
        new_sentence =new.join(i)
        return new_sentence
    return sentence

print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx")) 

Output:

aaa bbb aaa xxx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文