Remove the second 'o' from the statement 'helloworld' in python

407 Views Asked by At

Beginner in python here:

for l in 'helloworld':
    if l == 'w':
        continue
    lnew = l
    lnew = ''.join(lnew).replace('o', '').split()
    print "The letter is", lnew

I am trying to remove the letter 'o' after letter 'w' from 'helloworld'. I understand that continue statement returns the control to the beginning of the while loop. But how do I make sure that it skips 'o' after the letter 'w' when it runs through.

I could have done l == 'wo' but that would defeat the purpose of learning.

Instead I tried to make a new list, where it would replace the letter 'o' with ' ' (blank) and then split the list but it replaces both 'o' as I get the following:

The letter is ['h']
The letter is ['e']
The letter is ['l']
The letter is ['l']
The letter is []
The letter is []
The letter is ['r']
The letter is ['l']
The letter is ['d']

What should I do so that only the letter 'o' after letter 'w' is removed after continue statement skips over the letter 'w'. (The answer should look like this)

The letter is h
The letter is e
The letter is l
The letter is l
The letter is o
The letter is r
The letter is l
The letter is d
4

There are 4 best solutions below

0
On

You can use string.rindex to find the right most o. There are other options too, look here: If we cannot find 'o' ValueError is raised and we will just pass making str2 same as str1

str1 = 'helloworld'
str2 = str1
try:
    idx = str1.rindex('o')
    str2=str1[:idx] + str1[idx+1:]
except ValueError:
    pass
print "\n".join(str2)

Output

h
e
l
l
o
w
r
l
d
0
On

I hope I understand what you meant. I changed the code a bit:

string = 'helloworld'
new_string = ''

is_second_o = False

for char in string:
    if char == 'o':
        if not is_second_o:
            new_string += char
        is_second_o = True
    else:
        new_string += char


print new_string

output:

hellowrld

So what I did was iterate over the string, and check if the current char is 'o' if yes - i'm using a boolean flag to check if it's the first one.

If the current char isn't 'o', just append it to the new_string

0
On

Another approach:

w_found = False
for l in 'helloworld':
    if l == 'w':
        w_found = True
    if w_found and l == 'o': # skip this o as it comes after w
        continue
    print "The letter is", l

This prints:

The letter is h
The letter is e
The letter is l
The letter is l
The letter is o
The letter is w
The letter is r
The letter is l
The letter is d
0
On

Probably not the goal of the exercise, just curious:

'o'.join(term.replace('o', '') for term in 'helloworld'.split('o', 1))