svn_21
svn_21

Reputation: 17

Turning a String Decimal To String Int by Using Regex

I have below string;

line='P1: 6.0, P2: 5.0, P3: 10.3, P4: 7.0, P5: 10.0, P6: 6.0, P7: 4.0, P8: 5.8, P9: 5.0, P10: 5.0'

I only want to delete .0's and keep the values like 4.5 or 10.3. So what I want is like,

line='P1: 6, P2: 5, P3: 10.3, P4: 7, P5: 10, P6: 6, P7: 4., P8: 5.8, P9: 5, P10: 5'

I tried to do this,

import re
re.sub(r'.0(?=,)','',line)

It didn't work. I would appreciate any help.

Upvotes: 1

Views: 40

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

re.sub(r'\b\.0\b', '', line)

See regex proof.

Node Explanation
\b the boundary between a word char (\w) and something that is not a word char
\. '.'
0 '0'
\b the boundary between a word char (\w) and something that is not a word char

Python code:

import re
regex = r"\b\.0\b"
test_str = "P1: 6.0, P2: 5.0, P3: 10.3, P4: 7.0, P5: 10.0, P6: 6.0, P7: 4.0, P8: 5.8, P9: 5.0, P10: 5.0"
print(re.sub(regex, "", test_str))

Results: P1: 6, P2: 5, P3: 10.3, P4: 7, P5: 10, P6: 6, P7: 4, P8: 5.8, P9: 5, P10: 5

Upvotes: 1

marcos
marcos

Reputation: 4510

U can just do a simple replace, for example:

line = "P1: 6.0, P2: 5.0, P3: 10.3, P4: 7.0, P5: 10.0, P6: 6.0, P7: 4.0, P8: 5.8, P9: 5.0, P10: 5.0"


print(line.replace('.0', ''))
>>> P1: 6, P2: 5, P3: 10.3, P4: 7, P5: 10, P6: 6, P7: 4, P8: 5.8, P9: 5, P10: 5

Upvotes: 1

Related Questions