[Tutor] space between words printed

Alan Gauld alan.gauld at btinternet.com
Sun Nov 3 10:20:38 CET 2013


On 03/11/13 03:18, Byron Ruffin wrote:
> The output generates a sentence made up of words chosen randomly from
> lists.  I am having trouble getting a space between each of the words.

You probably want to look at the join() method of strings.
It joins a list of strings together using a separator...

You might also find string formatting helpful for some elements.

Alternatively you could just insert spaces into your string as you 
assemble it, but I think your wordlist() would be better returning a 
list of chosen words and you can then assemble/format that into as 
printable string outside the function.

HTH,

> import random
>
> def wordList():
>      adj1 = ["Big",        "Small",  "Early",  "Late",    "Red",
>              "Tall",    "Short"]
>      subj = ["politician", "man",    "woman",  "whale",   "company",
>              "child",   "soldier"]
>      obj =  ["budget",     "money",  "box",    "gift",    "gun",
>              "tank",    "drone"]
>      adj2 = ["hot",        "crazy",  "stupid", "fast",    "worthless",
>              "awesome", "dirty"]
>      verb = ["spends",     "shoots", "evades", "pursues", "subverts",
>              "passes",  "flirts"]
>
>      y = adj1[generate()], subj[generate()] + obj[generate()] +
> adj2[generate()] + verb[generate()]
>
>      return y

Notice that the first term is not added, it is returned as a separate 
value. Is that deliberate? I suspect ypou'd be better returning them all 
that way.

> def generate():
>      random0_6 = random.randint(0, 6)
>      return random0_6
>
> def main():
>      print (wordList(), ".", sep="")
>
>
> main()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list