简体   繁体   中英

Python - Remove a specific after a specific character?

How do i remove a specific after a specific charactor or value in the string?

My string looks like:

Name: 33 KG: 5.0 Name: 19 KG: 404.0 Name: 93 KG: 17.0

I would like it to look like:

Name33 KG:5 Name19 KG:404 Name93 KG:17 

I need to remove the : and the space behind Name, I would also like to remove the . and the 0 behind KG

The problem is i don't want to remove all the spaces : and all the 0

Try this:

>>> import re
>>>
>>> pattern = re.compile(
...     "(?<=\:)"   # Look for :
...     " "         # Match space
...     "([0-9]+)"  # Number to keep \1
...     "(?:\.0)?") # Optional .0
>>> pattern.sub("\\1", "Name: 33 KG: 5.0 Name: 19 KG: 424.0 Name: 93 KG: 17.0")
'Name:33 KG:5 Name:19 KG:424 Name:93 KG:17'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM