2010-02-17 17 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 
相關問題