1

I was practicing some regex using re module. I wonder how can we change only some numbers from the string.

a1 = 'images1/b100.png'

# required:
a2 = 'images2/b100.png'

My attempt:

import re
a1 = 'images1/b100.png'
nums = list(map(int, re.findall(r'\d+', a1)))
num0 = nums[0]
a2 = a1.replace(str(num0), str(num0+1))
2
  • Which number do you want to specifically change. Yes I know you want to change the 1 to 2, but which number do you want to change generally? Is it to always change the first digit to a 2? Or add one to the first number? Or change the first number that's before a / to a 2? It also would be great if you could show more examples of inputs and your desired output. Commented Apr 1, 2019 at 17:27
  • @Sweeper only the first number found in the string. Commented Apr 1, 2019 at 17:37

4 Answers 4

2

You can provide an argument to only replace the first occurence.

Change:

a2 = a1.replace(str(num0), str(num0+1))

To:

a2 = a1.replace(str(num0), str(num0+1), 1)

As mentioned here: https://docs.python.org/3/library/stdtypes.html

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Sign up to request clarification or add additional context in comments.

Comments

1

Below is the Answer,

a2.replace("b200","100")

Result: 'images2/100.png'

Please let me know if you have any questions.

Comments

1

you could type:

a2 = a1.replace(str(num0), str(num0+1), 1)

Comments

0
import re
a1 = 'images1/b100.png'
matches = re.match( r'^(.*)(\d+)(\/.*)$', a1)
a2 = matches.group(1)+str(int(matches.group(2))+1)+matches.group(3)

^(.*)(\d+)(\/.*)$: A path ending with a digit and any filename.

1 Comment

For 'images1/folder100/hello1.png' required is 'images2/folder100/hello2.png' This answer gives different result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.