简体   繁体   English

如何替换字符串 python 中的特定文本?

[英]How can I replace a specific text in string python?

I'm confused when trying to replace specific text in python我在尝试替换 python 中的特定文本时感到困惑

my code is:我的代码是:

Image = "/home/user/Picture/Image-1.jpg"
Image2 = Image.replace("-1", "_s", 1)
print(Image)
print(Image2)

Output: Output:

/home/user/Picture/Image-1.jpg
/home/user/Picture/Image_s.jpg

The output what I want from Image2 is: /home/user/Picture/Image-1_s.jpg我想从 Image2 得到的 output 是: /home/user/Picture/Image-1_s.jpg

You are replacing the -1 with _s您正在用_s替换-1

If you want to keep the -1 as well, you can just add it in the replacement如果你也想保留 -1 ,你可以将它添加到替换中

Image = "/home/user/Picture/Image-1.jpg"
Image2 = Image.replace("-1", "-1_s", 1)
print(Image)
print(Image2)

Output Output

/home/user/Picture/Image-1.jpg
/home/user/Picture/Image-1_s.jpg

If the digits can be variable, you can also use a pattern with for example 2 capture groups, and then use those capture groups in the replacement with _s in between如果数字可以可变,您还可以使用带有例如 2 个捕获组的模式,然后在替换中使用这些捕获组,中间使用_s

import re

pattern = r"(/home/user/Picture/Image-\d+)(\.jpg)\b"
s = "/home/user/Picture/Image-1.jpg\n/home/user/Picture/Image-2.jpg"

print(re.sub(pattern, r"\1_s\2", s))

Output Output

/home/user/Picture/Image-1_s.jpg
/home/user/Picture/Image-2_s.jpg

Or for example only taking the /Image- into account and then use the full match in the replacement instead of using capture groups:或者例如只考虑/Image- ,然后在替换中使用完全匹配而不是使用捕获组:

import re

pattern = r"/Image-\d+(?=\.jpg)\b"
s = "/home/user/Picture/Image-1.jpg\n/home/user/Picture/Image-2.jpg"
print(re.sub(pattern, r"\g<0>_s", s))

Output Output

/home/user/Picture/Image-1_s.jpg
/home/user/Picture/Image-2_s.jpg

The behaviour of the code you wrote is working as I would have expected from reading it.您编写的代码的行为正如我阅读它所期望的那样。 Now, as to how to correct it to do what you expected/wanted it to do is a little different.现在,至于如何纠正它来做你期望/想要它做的事情有点不同。 You don't necessarily need to replace here, instead, you can consider appending what you need, as it seems from the behaviour you are looking for is in fact appending something to the end of the path before the extension.你不一定需要在这里替换,相反,你可以考虑附加你需要的东西,因为从你正在寻找的行为看来,实际上是在扩展之前的路径末尾附加一些东西。

We can try to help the code a bit by making it a little more "generic" by allowing us to simply "append" anything to the end of a string.我们可以尝试通过允许我们简单地将任何内容“追加”到字符串的末尾来使代码更“通用”一点,从而对代码有所帮助。 The steps we can do to achieve this is (for other readers, yes there are more foolproof ways to do this, for now sticking to a simple example):我们可以做的步骤是(对于其他读者,是的,有更多简单的方法可以做到这一点,现在坚持一个简单的例子):

  • split the string at .在 处拆分字符串. so that you end up with a list containing:这样您最终会得到一个包含以下内容的列表:

["/home/user/Picture/Image-1", "jpg"]

  • Append to the first element what you need to the end of the string so you end up with: Append 到第一个元素,你需要到字符串的末尾,所以你最终得到:

"/home/user/Picture/Image-1_s"

  • Use join to re-craft your string, but use .使用join重新制作您的字符串,但使用. : :

".".join(["/home/user/Picture/Image-1_s", "jpg"])

  • You will finally get:你最终会得到:

/home/user/Picture/Image-1_s.jpg

Coding the above, we can have it work as follows:对上面的代码进行编码,我们可以让它按如下方式工作:

>>> Image1 = "/home/user/Picture/Image-1.jpg"
>>> img_split = Image1.split(".")
>>> img_split
['/home/user/Picture/Image-1', 'jpg']
>>> img_split[0] = img_split[0] + "_s"
>>> img_split
['/home/user/Picture/Image-1_s', 'jpg']
>>> final_path = ".".join(img_split)
>>> final_path
'/home/user/Picture/Image-1_s.jpg'

More idiomatic approach using Python's pathlib module is an interesting solution too.使用 Python 的pathlib模块的更惯用的方法也是一个有趣的解决方案。

from pathlib import Path

Image1 = "/home/user/Picture/Image-1.jpg"
p = Path(Image1)

# you have access to all the parts you need. Like the path to the file:
p.parent # outputs PosixPath('/home/user/Picture/')

# The name of the file without extension
p.stem # outputs 'Image-1'

# The extension of the file
p.suffix # outputs '.jpg'

# Finally, we get to now rename it using the rename method!

p.rename(p.parent / f"{p.stem}_s{p.suffix}")

# This will now result in the following object with renamed file!
# PosixPath('/home/user/Picture/Image-1_s.jpg')

The replace function replaces "-1" with "_s" . replace function"-1"替换为"_s"

If you want the output to be: /home/user/Picture/Image-1_s.jpg如果您希望 output 为: /home/user/Picture/Image-1_s.jpg

You should replace "-1" with "-1_s" .您应该将"-1"替换为"-1_s"

Try:尝试:

Image = "/home/user/Picture/Image-1.jpg"
Image2 = Image.replace("-1", "-1_s")
print(Image)
print(Image2)

Try this尝试这个

i think you should append the string in a certain position not replace我认为你应该 append 某个 position 中的字符串不替换

Image = "/home/user/Picture/Image-1.jpg"
Image2 = Image[:26]+ '_s' + Image[26:]
print(Image2)

The output output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM