Select all string in list and append a string – python

Question:

I wanna add "." to the end of any item of doing variable.
and I want output like this => I am watching.

import random
main = ['I', 'You', 'He', 'She']
main0 = ['am', 'are', 'is', 'is']
doing = ['playing', 'watching', 'reading', 'listening']
rd = random.choice(main)
rd0 = random.choice(doing)
result = []
'''
if rd == main[0]:
    result.append(rd)
    result.append(main0[0])
if rd == main[1]:
    result.append(rd)
    result.append(main0[1])
if rd == main[2]:
    result.append(rd)
    result.append(main0[2])
if rd == main[3]:
    result.append(rd)
    result.append(main0[3])
'''
result.append(rd0)
print(result)

well, I tried those codes.

'.'.append(doing)
'.'.append(doing[0])
'.'.append(rd0)

but no one of them works, and only returns an error that:

Traceback (most recent call last):
  File "c:Users----DocumentsCodesTestings.py", line 21, in <module>
    '.'.append(rd0)
AttributeError: 'str' object has no attribute 'append'

Answers:

Why not just select a random string from each list and then build the output as you want:

import random
main = ['I', 'You', 'He', 'She']
verb = ['am', 'are', 'is', 'is']
doing = ['playing', 'watching', 'reading', 'listening']
p1 = random.choice(main)
p2 = random.choice(verb)
p3 = random.choice(doing)

output = ' '.join([p1, p2, p3]) + '.'
print(output)  # You is playing.

Bad English, but the logic seems to be what you want here.

Answered By: Tim Biegeleisen

Just add a period after making the string:

import random

main = ['I', 'You', 'He', 'She']
main0 = ['am', 'are', 'is', 'is']
doing = ['playing', 'watching', 'reading', 'listening']

' '.join([random.choice(i) for i in [main, main0, doing]]) + '.'
Answered By: RJ Adriaansen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.