Home > database >  How do i join 2 strings the right way
How do i join 2 strings the right way

Time:04-21

My problem is that this code only prints out "a"

print(str(random.randint(1, 2)).join(str("a")))

CodePudding user response:

join is used to concatenate elements of an iterable. What you need is the operator, so:

print(str(random.randint(1, 2)) "a")

You also don't need to cast "a" to string (it is a string already).

CodePudding user response:

.join() does not do what you think it does. What I think you actually want is string concatenation, which is done using the operator. Also, the str() around "a" is unnecessary as it is already a string.

Here is the corrected code:

import random
print(str(random.randint(1, 2))   "a")

CodePudding user response:

i didn't get what actually but: a='test'
print(str(random.randint(1, 2)).join(str(" a")))'
output : t2e2s2t

CodePudding user response:

I would use string formatting:

>>> import random

>>> '{}a'.format(random.randint(1, 2))
'1a'
  • Related