0

Here is the code that I have used and reference in this post:

alpha=["One", "Two", "Three"]
beta=["One", "Two", "Three"]
charlie=["One", "Two", "Three"]
import random
alpharandom=random.randint(0,2)
betarandom=random.randint(0,2)
charlierandom=random.randint(0,2)
stringcode=(alpha[alpharandom],beta[betarandom],charlie[charlierandom])
stringcodetwo=str(stringcode).replace(" ", "")
print(stringcodetwo)

I am using python 3.0 to generate a random string using predefined items from lists. This results in an output similar to:

('Two','One','Two')

However, would it be possible to generate so that the brackets, commas and quotation marks are omitted? I have tried the replace function, but that only seems to work for the spaces between the generated string. An example of a desired output would be:

TwoOneTwo
martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

You can use the .join string method instead of replace.

Instead of: stringcodetwo=str(stringcode).replace(" ", "")

Do: stringcodetwo="".join(stringcode)

newToCoding
  • 174
  • 1
  • 1
  • 8
1

The reason your output has brackets and commas is that you are printing a tuple.

stringcode=(alpha[alpharandom],beta[betarandom],charlie[charlierandom])

This line is creating a tuple of 3 strings.

There are many ways to join the string values to make a single string.

Any easy way would be:

"".join(stringcode)

Essentially it iterates through the values of the iterable (the tuple stringcode in this case) and joins them into a string separated by "" (so just joins the strings with nothing in between)

You could also just directly create a string instead of a tuple (if that's what you need):

stringcode = alpha[alpharandom] + beta[betarandom] + charlie[charlierandom]
print (stringcode)

As each of the individual elements are strings, we are just concatenating them and storing them in stringcode.

For which method is better, this question can provide some insight: How slow is Python's string concatenation vs. str.join?

Read more about tuples here and join in python here.

Stuti Rastogi
  • 1,162
  • 2
  • 16
  • 26
0

You can use loop to iterate over a set and with the use of end ="". you can remove the newline.

alpha=["One", "Two", "Three"]
beta=["One", "Two", "Three"]
charlie=["One", "Two", "Three"]
import random
alpharandom=random.randint(0,2)
betarandom=random.randint(0,2)
charlierandom=random.randint(0,2)
stringcode=(alpha[alpharandom],beta[betarandom],charlie[charlierandom])
for i in range(len(stringcode)):
  print(stringcode[i], end="")
Code With Faraz
  • 62
  • 2
  • 12