0

So I have a number like 7.50x, which I want to convert to 7.5x. I thought about using regular expressions. I can easily match this expression, for example by using re.search('[0-9].[0-9]0x', string). However, I'm confused how to replace every such number using the re.sub method. For example what should be there as the second argument?

re.sub('[0-9].[0-9]0x', ?, string)

3 Answers 3

2
re.sub(r'([0-9]\.[0-9])0x', r'\1x', num)

Test

>>> import re
>>> num="7.50x"
>>> re.sub(r'([0-9]\.[0-9])0x', r'\1x', num)
'7.5x'
  • r'\1x' here \1 is the value saved from the first capturing group, ([0-9]\.[0-9])

    eg for input 7.50x the capturing group matches 7.5 which saved in \1

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

6 Comments

Can you explain what does r'\1x' really mean?
@MetallicPriest I have edited the answer. Hope its clear for you
That is awesome. Thanx for the answer. I think putting parantheses around [0-9].[0-9] is must here, so that it can be seen as first element \1. From this, I also infer that indexing for captured groups start from 1 rather than 0. Right?
@MetallicPriest You are awesome !!! The capturing group is those enclused in paranthesis. and off course they begin with 1. Also they are numbered from left to right. Hope you got that too :)
You must need to escape the dot.
|
1
0+(?![1-9])(?=[^.]*$)

Try this.See demo.

http://regex101.com/r/hQ9xT1/14

x=7.50x
re.sub(r"0+(?![1-9])(?=[^.]*$)","",x)

1 Comment

My question was not how to search it, but how to replace it.
1

Using positive lookahead and lookbehind assertion.

>>> import re
>>> num="7.50x"
>>> re.sub(r'(?<=\d\.\d)0(?=x)', r'', num)
'7.5x'
  • (?<=\d\.\d), the number which precedes the digit 0 would be in this digit dot digit format.
  • And the character following the match (0) must be x

  • \. Matches a literal dot.

Comments

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.