How can I replace the first occurrence of a character in every word?
Say I have this string:
hello @jon i am @@here or @@@there and want some@thing in '@here" # ^ ^^ ^^^ ^ ^
And I want to remove the first @
on every word, so that I end up having a final string like this:
hello jon i am @here or @@there and want something in 'here # ^ ^ ^^ ^ ^
Just for clarification, "@" characters always appear together in every word, but can be in the beginning of the word or between other characters.
I managed to remove the "@" character if it occurs just once by using a variation of the regex I found in Delete substring when it occurs once, but not when twice in a row in python, which uses a negative lookahead and negative lookbehind:
@(?!@)(?<!@@)
See the output:
>>> s = "hello @jon i am @@here or @@@there and want some@thing in '@here" >>> re.sub(r'@(?!@)(?<!@@)', '', s) "hello jon i am @@here or @@@there and want something in 'here"
So the next step is to replace the "@" when it occurs more than once. This is easy by doing s.replace('@@', '@')
to remove the "@" from wherever it occurs again.
However, I wonder: is there a way to do this replacement in one shot?
>>> help(str. replace) Help on method_descriptor: replace(...) S. replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
To replace the first occurrence of a character in Java, use the replaceFirst() method.
To replace or substitute all occurrences of one character with another character, you can use the substitute function. The SUBSTITUTE function is full automatic. All you need to do is supply "old text" and "new text". SUBSTITUTE will replace every instance of the old text with the new text.
I would do a regex replacement on the following pattern:
@(@*)
And then just replace with the first capture group, which is all continous @ symbols, minus one.
This should capture every @
occurring at the start of each word, be that word at the beginning, middle, or end of the string.
inp = "hello @jon i am @@here or @@@there and want some@thing in '@here" out = re.sub(r"@(@*)", '\\1', inp) print(out)
This prints:
hello jon i am @here or @@there and want something in 'here
How about using replace('@', '', 1)
in a generator expression?
string = 'hello @jon i am @@here or @@@there and want some@thing in "@here"' result = ' '.join(s.replace('@', '', 1) for s in string.split(' ')) # output: hello jon i am @here or @@there and want something in "here"
The int value of 1
is the optional count
argument.
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With