Home > Net >  Removing index from a string using while loop
Removing index from a string using while loop

Time:09-10

I don't know why but the code I wrote isn't running. I'm trying to generate a random index and deleting it from the string. It's not giving me an error message so I don't know what's wrong. Here's what I have:

def delete_randomly(string):
  i = 0
  while i < len(string):
    if string[i] == randint(0, 10):
      return string.remove(string[i])

CodePudding user response:

This infinite loop will never break depending on the input. Is this what you trying to achieve?

from random import randint
def delete_randomly(string):
  print(f'input string = {string}')
  ran_int = randint(0, len(string))
  print(f'removing index = ({ran_int})')
  new_str = ''
  for idx, val in enumerate(string):
      if idx == ran_int:
          continue
      new_str =val
  return new_str
print(delete_randomly('abakdkemnaskakac'))

CodePudding user response:

As an addition for @Juan Antonio Martinez Lopez answer's, you could also use the following code:

def delete_randomly(string):
  randomIndex = randint(0, len(string) - 1)
  return string[:randomIndex]   string[randomIndex   1:]

CodePudding user response:

You are in an infinite loop. Imagine the string is 'stackoverflow', your code is always comparing string[0] (because i == 0 everytime) with a random number between 0-10. For example

First iteration:

string[0] = 's'

randint(0, 10) = 3

Second iteration:

string[0] = 's'

randint(0, 10) = 7

Infinite iteration

string[0] = 's'

randint(0, 10) = number

Never 's' would be equals to number.

It is also wrong because string class in python has no method named remove.

So if you want remove a valid letter the code is:

def delete_randomly(string):
    temp = list(string)
    temp[randint(0, len(string) - 1)] = ""
    return "".join(temp)
  • Related