How to replace part of string with another string?

Question:

I have a list of strings as follows:

generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]

I am trying to replace the string after between the two #s with za

expected response

generator = ["one#za#two1", "one#za#two2", "one#za#two3", "one#za#two4"]

I tried the following and it doesn’t work

import re

generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]
generator2 = []
for g in generator:
    generator2.append(re.sub(r'one#za[a-zA-z]#', 'one#za#', g))
    
print(generator2)

What is the mistake I am doing?

Asked By: some_programmer

||

Answers:

Try

re.sub(r'#([a-zA-z]*)#', '#za#', g)
Answered By: JarroVGIT
import re
generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]
generator2 = []
for g in generator:
    generator2.append(re.sub('#[^#]*#', '#za#', g))
print(generator2)

Result :
['one#za#two1', 'one#za#two2', 'one#za#two3', 'one#za#two4']

Answered By: EL-AJI Oussama
def replace_with_za(str) :
  chunks = str.split("#")
  return chunks[0]+"#za#"+chunks[-1]
Answered By: Utkarsh
import re

generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]
generator2 = []
for g in generator:
    generator2.append(re.sub(r'one#za[a-zA-Za-z]+#', 'one#za#', g))
    
print(generator2)

Try the above one.

Answered By: creatorpravin

Try the following code if you want to change all the strings in the list:

import re

generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]
for i in range(len(generator)):
    generator[i] = generator[i].replace(re.search(r'#(.*?)#', generator[i]).group(1), 'za')

when you call print(generator) the output is:
['one#za#two1', 'one#za#two2', 'one#za#two3', 'one#za#two4']

Answered By: tangorboyz

You don’t need re for this trivial use-case.

Just split each string on the hash character then reconstruct it thus:

generator = ["one#zade#two1", "one#zaat#two2", "one#zach#two3", "one#zanl#two4"]

generator = [f'{left}#za#{right}' for left, _, right in map(lambda s: s.split('#'), generator)]
Answered By: Fred
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.