Home > database >  Cannot remove the right end space of the output string
Cannot remove the right end space of the output string

Time:11-06

import random
string = ''

keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)

for i in range(temp):
    string = string   random.choice(keys)   ' '

string.strip()
print(string)

I'm just learning programming Even if you use the strip function, the space on the right end does not disappear.

What did I do wrong?

CodePudding user response:

The strip function returns the modified string but it does't modify the orignal string it only returns it which need to be stored in another string

import random
string = ''

keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)

for i in range(temp):
    string = string   random.choice(keys)   ' '

str=string.strip()
print(str)

CodePudding user response:

I suggest using a list comprehension along with string join() here:

keys = ["car", "banana", "groof", "jump", "king", "alley"]
temp = random.randint(2,3)
x = ' '.join([random.choice(keys) for i in range(temp)])
print(x)
  • Related