views:

53

answers:

5

Basicaly I have a user inputted string like:

"hi my name is bob"

what I would like to do is have 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

+4  A: 

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.

Seth
+1  A: 
s[:random.randrange(len(s))] + "DUR"
Ignacio Vazquez-Abrams
A: 

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.

Rishabh Manocha
A: 

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'
ghostdog74
A: 

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
luc