def word(s1,s2):
index = 0
while index < len(s1):
if s2 in range(len(s1)):
s1[index] = s1[index] * index
index = index 1
return s1
print(word("aratehadb", "a"))
I want the code to return "raatehaaaaaadb"
meaning I want it to multiply the chosen letter with the index its found at, I have tried
res = [i for i in range(len(s1)) if s1.startswith(s2, i)]
to find the positions that the letters are at but I'm stuck at how I multiply with the index
CodePudding user response:
Use enumerate
You can use enumerate to obtain the index of each value, determine if the letter matches what you want to multiply and do the multiplication if required.
def word(s1, s2):
return ''.join([l*i if l == s2 else l for i, l in enumerate(s1)])
print(word("aratehadb", "a"))
# raatehaaaaaadb
Closer from your first implementation
def word(s1, s2):
index = 0
# string can't be mutated (changed) so we need to create
# a list to change each character string and make it bigger
# if needed
l_s1 = list(s1)
while index < len(s1):
if s2 == s1[index]:
# Here you can replace s1 with l_s1, we access the same string anyway.
# Also, l_s1[index] *= index also works
l_s1[index] = s1[index] * index
index = index 1
return ''.join(l_s1)
print(word("aratehadb", "a"))
# raatehaaaaaadb