2010-02-17 61 views

回答

4

事情是这样的:

import random 

s = "hi my name is bob" 
r = random.randint(0, len(s)) 
print s[:r] + "DUR" 

字符串连接与+完成。 [a:b]表示法称为切片。 s[:r]返回s的第一个r个字符。

1
s[:random.randrange(len(s))] + "DUR" 
0

不知道为什么你会想,但你可以这样做以下

import random 
user_string = 'hi my name is bob' 
my_custom_string = 'DUR' 
print ''.join([x[:random.randint(0, len(user_string))], my_custom_string]) 

你应该为random模块读取the docs找出你应该使用哪种方法。

0

的许多方面

>>> import random 
>>> specified="DUR" 
>>> s="hi my name is bob" 
>>> s[:s.index(random.choice(s))]+specified 
'hi mDUR' 
0

可以使用随机模块只有一个。看下面的例子:

import random 
s = "hi my name is bob" 
pos = random.randint(0, len(s)) 
s = s[:pos] + "DUR" 
print s 
相关问题