Python is a powerful language that allows programmers to perform various tasks using built-in libraries. A random string, for example, can be generated using the built-in libraries. Two libraries are imported for this:
import string
import random
Using this random
module, different random strings can be generated.
random.choice()
is used to generate strings in which characters may repeat, while random.sample()
is used for non-repeating characters.
Method | Description |
---|---|
string.ascii_uppercase |
Returns a string with uppercase characters |
string.ascii_lowercase |
Returns a string with lowercase characters |
string.ascii_letters |
Returns a string with both lowercase and uppercase characters |
string.digits |
Returns a string with numeric characters |
string.punctuation |
Returns a string with punctuation characters |
import randomimport string# printing lowercaseletters = string.ascii_lowercaseprint ( ''.join(random.choice(letters) for i in range(10)) )# printing uppercaseletters = string.ascii_uppercaseprint ( ''.join(random.choice(letters) for i in range(10)) )# printing lettersletters = string.ascii_lettersprint ( ''.join(random.choice(letters) for i in range(10)) )# printing digitsletters = string.digitsprint ( ''.join(random.choice(letters) for i in range(10)) )# printing punctuationletters = string.punctuationprint ( ''.join(random.choice(letters) for i in range(10)) )