简体   繁体   中英

How to generate a random string without characters pertaining to a list, such as ','?

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

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

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

Do: stringcodetwo="".join(stringcode)

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 .

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="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM