1

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.

4
  • Please be more descriptive that "didn't work" - what happened? Error? Unexpected results? Commented Jan 30, 2021 at 21:39
  • Actually it works but not for the last element of the string. Output is ''P1: 6, P2: 5, P3: 10.3, P4: 7, P5: 10, P6: 6, P7: 4, P8: 5.8, P9: 5, P10: 5.0'' Commented Jan 30, 2021 at 21:42
  • You could also use re.sub(r'(?<=\d)\.0(?![^,])','',line) to make sure you only remove .0 after a digit and before a comma/end of string. Commented Jan 30, 2021 at 21:52
  • @Wiktor Stribiżew Wow! that looks complex, thanks a lot for clarification and the effort Commented Jan 30, 2021 at 22:08

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! It is much more easy :)
@svn_21 Try '5.05'.replace('.0', ''), do you expect this?
u can only use this like @WiktorStribiżew mentioned if they have only one decimal digit.
@Wiktor Stribiżew The data has only one decimal numbers, so above code worked for me
1

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

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.