Basicaly我有一個用戶輸入的字符串,如:如何隨機結束一個字符串,並在Python的最後連接另一個字符串?
「嗨,我的名字是鮑勃」
我想要做的是有我的程序隨機挑選的字符串一個新的結局和我指定的結束吧結尾。
例如:
「嗨,我叫杜爾。」
「hi mDUR」。
等等等等
我有點新的Python所以希望有一個簡單的解決這個嘿嘿
Basicaly我有一個用戶輸入的字符串,如:如何隨機結束一個字符串,並在Python的最後連接另一個字符串?
「嗨,我的名字是鮑勃」
我想要做的是有我的程序隨機挑選的字符串一個新的結局和我指定的結束吧結尾。
例如:
「嗨,我叫杜爾。」
「hi mDUR」。
等等等等
我有點新的Python所以希望有一個簡單的解決這個嘿嘿
事情是這樣的:
import random
s = "hi my name is bob"
r = random.randint(0, len(s))
print s[:r] + "DUR"
字符串連接與+
完成。 [a:b]
表示法稱爲切片。 s[:r]
返回s
的第一個r
個字符。
s[:random.randrange(len(s))] + "DUR"
不知道爲什麼你會想,但你可以這樣做以下
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找出你應該使用哪種方法。
的許多方面
>>> import random
>>> specified="DUR"
>>> s="hi my name is bob"
>>> s[:s.index(random.choice(s))]+specified
'hi mDUR'
可以使用隨機模塊只有一個。看下面的例子:
import random
s = "hi my name is bob"
pos = random.randint(0, len(s))
s = s[:pos] + "DUR"
print s