views:

226

answers:

3

Hi Alls,

I'd like to remove one char from a string like this:

string = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"

print len(string)

(33)

So i would like to remove one random char in this string, and then have a len = 32 What's the best way to do so ?

EDIT: thanks for your answers, but i forgot something: i'd like to print the char removed; Using Anurag Uniyal technique ?

Thanks !

+5  A: 
>>> import random
>>> s = "ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
>>> i = random.randint(0, len(s)-1)
>>> print s[:i] + s[i+1:]
ASDFVGHFJHRSFDZFDJKUYRDSEADFDHDS
>>> print s[i]
T

Basically get a random number from 0 to len-1 of string and remove the char at that index in string, you may convert string to list, del the item and re join but this will be faster and easier to read

Anurag Uniyal
+3  A: 
import random

index = random.randint(0, len(yourstring)-1)
yourstring = yourstring[:index] + yourstring[index+1:]

print yourstring[index]
jellybean
+8  A: 
>>> s="ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
>>> r=random.randrange(len(string))
>>> print s[:r]+s[r+1:]
ASDFVGHJHRSFDZFDJKUYTRDSEADFDHDS
ghostdog74
+1 for using the right function, randrange -- randint is weirdly incompatible with normal Python conventions ("right-bound always excluded") and really grates on me!-)
Alex Martelli