Remove second 'o' from 'helloworld' expression in python

Beginner in python:

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 the continue statement returns the control to the beginning of the while loop. But how can I make sure it skips the 'o' after the 'w' when it passes.

I could do l == 'wo' , but that might interfere with the learning goal.

Instead, I tried to create a new list in which it would replace the letter 'o' with '' (space) and then split the list, but replace as 'o' as I get this:

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 to remove only the 'o' after the 'w' after the continue statement skips the '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

      

+3


source to share


4 answers


I hope I understand what you mean. 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 loop over the string and check if the current char is 'o', if yes - I use a boolean flag to check if it is the first one.

If the current char is not "o" then just add it to new_string

0


source


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

      



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


source


You can use string.rindex to find the best fit. There are other options, take a look here : If we can't find the 'o' ValueError and we just pass make str2 the 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


source


Probably not the purpose of the exercise, just curious:

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

      

0


source







All Articles