'Replacing words inside the string with that of dictionary without using any kind of replace function [closed]
expected output = "Hello. My name is $xyz$. I am from $abc$.
# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
if string[i]=='#':
arr.append(i)
#print(arr)
indices = []
for i in range(len(arr)):
if i%2 != 0:
continue
else:
indices.append(arr[i]+1)
#print(indices)
sources = []
l = 0
while l<len(arr):
sources.append(string[arr[l]+1:arr[l+1]])
#print(l, sources)
l+=2
#print(sources)
targets = toReplace.values()
#print(targets)
for index, source, target in zip(indices, sources, targets):
#print(index, source, target)
if not string[index:].startswith(source):
continue
else:
modified[index] = target
#print(modified)
for i in range(index+1,len(source)+index):
modified[i] = ''
print("".join(modified))
should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??
Solution 1:[1]
Good day to you! I'm glad if the following code will help you in anyway. I have used regular expression to get the required output. Here you go,
import re
string = "Hello. My name is $something1$. I am from $something2$."
dict = {'something1':'xyz', 'something2':'abc'}
for k,v in zip(dict.keys(),dict.values()):
string=re.sub(k,v,string)
print(string)
And Output is :
Hello. My name is $xyz$. I am from $abc$.
I'm really glad for this opportunity to help you! Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nithya Bharatkumar |
