开发者

Remove one char from a string

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 ?

开发者_JAVA技巧

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

Thanks !


>>> s="ASDFVGHFJHRSFDZFDJKUYTRDSEADFDHDS"
>>> r=random.randrange(len(string))
>>> print s[:r]+s[r+1:]
ASDFVGHJHRSFDZFDJKUYTRDSEADFDHDS


>>> 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


import random

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

print yourstring[index]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜