apfel
apfel

Reputation: 13

replace method replaces similar characters how do i make it replace a single specific ones

I'm trying to loop through a string & uppercase each character using replace method.

def wave(p):
    if isinstance(p, str):
        lst = []
        p.lower()
        for i in range(0, len(p)):
            lst.append(p.replace(p[i], p[i].upper()))
        return lst

it works but the problem is that if I for example used the function on the word "hello" this is what the output would be

['Hello', 'hEllo', 'heLLo', 'heLLo', 'hellO']

so it uppercased the two L's while I want it to uppercase one L at a time. How do i make that?

Upvotes: 1

Views: 71

Answers (4)

Rachel Cynthia
Rachel Cynthia

Reputation: 126

Instead of using replace, you have to do it manually.
This will work for your requirements:

for i in range(0,len(p)):
    s = ''
    for j in range(len(p)):
        if(i == j):
            s = s + p[i].upper()
        else:
            s = s + p[j]
    lst.append(s)

Hope this helps!

Upvotes: 0

Shubham Periwal
Shubham Periwal

Reputation: 2248

You dont need to use the .replace() function. Thanks @kmmanoj for the clarity.

def wave(p):
    if isinstance(p, str):
        lst = []
        p.lower()
        for i in range(0, len(p)):
            lst.append(p[:i] + p[i].upper() + p[i+1:])
        return lst

['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521987

Here is a list comprehension version:

def wave(p):
    lst = [p] * len(p)
    return [x[:i].lower() + x[i:].capitalize() for i, x in enumerate(lst)]

print(wave('hello'))  # ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

Upvotes: 2

kmmanoj
kmmanoj

Reputation: 196

Manipulate and log as the loop iterates through each character of the string.

def wave(p):
    if isinstance(p, str):
        lst = []
        p.lower()
        for i in range(0, len(p)):
            p_frame = p[:i] + p[i].upper() + p[i+1:]
            lst.append(p_frame)
        return lst

Upvotes: 0

Related Questions