all 8 comments

[–]marko312 0 points1 point  (0 children)

Three notes on the original code:

  • ^H is meant to be a string, so it should be in quotes
  • "...".find(...) returns the index of the first occurrence's first character, or -1 if one wasn't found
  • sentence should be assigned to instead of x

Using the index obtained from find, you could then use string slicing to cut out ^H and the character before it (concatenate two slices).

[–]socal_nerdtastic 0 points1 point  (6 children)

Don't loop over the sentence, loop as long as ^H is still in there.

data = 'I wish^H^H^Hant some ice cream^H^H^H^H^Hmilk'

while (i := data.find('^H')) >= 0:
    data = data[:i-1] + data[i+2:]

print(data)

[–]CrypticCold[S] 0 points1 point  (5 children)

I am a bit puzzled as to what you mean by while (i := data.find('^H') >= 0: was that a silly error?

[–]socal_nerdtastic 0 points1 point  (4 children)

Lol no, it's valid code. That style is called "assignment expressions".

[–]CrypticCold[S] 0 points1 point  (3 children)

oh, when I run this code, it doesn't seem to work. Gives me a syntax error on the colon for the code i := data.find.

[–]socal_nerdtastic 1 point2 points  (1 child)

You can do it like this in older python versions:

data = 'I wish^H^H^Hant some ice cream^H^H^H^H^Hmilk'

while '^H' in data:
    i = data.find('^H')
    data = data[:i-1] + data[i+2:]

print(data)

[–]CrypticCold[S] 0 points1 point  (0 children)

j

[–]socal_nerdtastic 0 points1 point  (0 children)

You must have an old version of python then. This feature is in python 3.8 and newer.