How can I replace a specific text in string python?

Question:

I’m confused when trying to replace specific text in python

my code is:

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

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

Asked By: Varga Ignacio

||

Answers:

You are replacing the -1 with _s

If you want to keep the -1 as well, you can just add it in the replacement

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

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

import re

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

print(re.sub(pattern, r"1_s2", s))

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:

import re

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

Output

/home/user/Picture/Image-1_s.jpg
/home/user/Picture/Image-2_s.jpg
Answered By: The fourth bird

The replace function replaces "-1" with "_s".

If you want the output to be: /home/user/Picture/Image-1_s.jpg

You should replace "-1" with "-1_s".

Try:

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

Try this

i think you should append the string in a certain position not replace

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

The output

enter image description here

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:

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

  • Use join to re-craft your string, but use .:

".".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.

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')
Answered By: idjaw
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.