Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16862

string.replace replacing all occurences

$
0
0

I'm trying to make string.replace replace all words except ones starting with a certain character, e.g. ~, but if i have a word with only one letter, that letter gets deleted from the words i want to stay

Code

import rest1 = "dolphin fish ~shark eel octopus ~squid a"for i in re.findall(r"\b(?<!~)\w+", st1):    st1 = st1.replace(i, "")print(st1)

What I want to happen:

Input:"dolphin fish ~shark eel octopus ~squid a"

Output:"~shark ~squid"

What happens:

Input:"dolphin fish ~shark eel octopus ~squid a"

Output:"~shrk ~squid"

I think this is happening because it's replacing all instances of 'a', including the ones within other words. How do I ensure it only deletes the instance intended?


Viewing all articles
Browse latest Browse all 16862

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>