How can I replace the first occurrence of a character in every word?

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.


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

You can use re.sub like this:

import re

s = "hello @jon i am @@here or @@@there and want some@thing in '@here"
s = re.sub('@(\w)', r'\1', s)
print(s)

That will result in:

"hello jon i am @here or @@there and want something in 'here"

And here is a proof of concept:

>>> import re
>>> s = "hello @jon i am @@here or @@@there and want some@thing in '@here"
>>> re.sub('@(\w)', r'\1', s)
"hello jon i am @here or @@there and want something in 'here"
>>> 

Was pondering for cases what if only the last char is @ and you don't want to remove it, or you have specific allowed starting chars, came up with this:

>>> ' '.join([s_.replace('@', '', 1) if s_[0] in ["'", "@"] else s_ for s_ in s.split()])
"hello jon i am @here or @@there and want some@thing in 'here"

Or, suppose you want to replace @ only if it is in first n characters

>>> ' '.join([s_.replace('@', '', 1) if s_.find('@') in range(2) else s_ for s_ in s.split()])
"hello jon i am @here or @@there and want some@thing in 'here"

Tags:

Python

Regex