In many cases we may need to generate random strings.
Python also provides methods and functions for generating random strings.
This function is choice, a function defined in the Random library.
Usually choice will pick one of the given strings.
According to Python’s official definition of strings in String.py.
whitespace = ' \t\n\r\v\f' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_letters = ascii_lowercase + ascii_uppercase digits = '0123456789' hexdigits = digits + 'abcdef' + 'ABCDEF' octdigits = '01234567' punctuation = r"""!" # $% & '() *, +, -. / :; The < = >? @[\]^_`{|}~""" printable = digits + ascii_letters + punctuation + whitespaceCopy the code
The above strings are ASCII strings you can use at any time.
When the choice(string.ascii_uppercase) method is called, it means that a character will be randomly selected from uppercase characters.
What if we want a random string of six lengths?
We should execute the above function six times and then concatenate the results of the six executions.
For example, we could write:
"".join([choice(printable) for x in range(int(length))])
Length is the length of the string we want to concatenate. Printable is a character that can be used to generate strings.
The structure of our code run, as shown above, is designed to test random string generation.
www.ossez.com/t/python/13…