开发者

How can I end a string randomly and concatenate another string at the end in Python?

开发者 https://www.devze.com 2022-12-20 04:40 出处:网络
Basicaly I have a user inputted string like: \"hi my name is bob\" what I would like to do is h开发者_JAVA百科ave my program randomly pick a new ending of the string and end it with my specified end

Basicaly I have a user inputted string like:

"hi my name is bob"

what I would like to do is h开发者_JAVA百科ave my program randomly pick a new ending of the string and end it with my specified ending.

For example:

"hi my name DUR."

"hi mDUR."

etc etc

I'm kinda new to python so hopefully there's an easy solution to this hehe


Something like this:

import random

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

String concatentation is accomplished with +. The [a:b] notation is called a slice. s[:r] returns the first r characters of s.


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


Not sure why you would want this, but you can do something like the following

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

You should read the docs for the random module to find out which method you should be using.


just one of the many ways

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


You can use the random module. See an example below:

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

精彩评论

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

关注公众号