ascii_letters in Python
Last Updated :
23 Oct, 2020
In Python3, ascii_letters is a pre-initialized string used as string constant.
ascii_letters is basically concatenation of ascii_lowercase and ascii_uppercase string constants. Also, the value generated is not locale-dependent, hence, doesn’t change.
Syntax :
string.ascii_letters
Note : Make sure to import string library function inorder to use ascii_letters.
Parameters :
Doesn't take any parameter, since it's not a function.
Returns :
Return all ASCII letters (both lower and upper case)
Code #1 :
import string
result = string.ascii_letters
print (result)
|
Output :
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Code #2 :
Given code checks if the string input has only ASCII characters or not.
import string
def check(value):
for letter in value:
if letter not in string.ascii_letters:
return False
return True
input1 = "GeeksForGeeks"
print (input1, "--> " , check(input1))
input2 = "Geeks for Geeks"
print (input2, "--> " , check(input2))
input3 = "Geeks_for_geeks"
print (input3, "--> " , check(input3))
|
Output :
GeeksForGeeks --> True
Geeks for Geeks --> False
Geeks_for_geeks --> False
Applications :
The string constant ascii_letters can be used in many practical applications.
Let’s see a code explaining how to use ascii_letters to generate strong random passwords of given size.
Code #1 :
import random
import string
def rand_pass(size):
generate_pass = ''.join([random.choice(
string.ascii_letters + string.digits)
for n in range (size)])
return generate_pass
password = rand_pass( 10 )
print (password)
|
Output :
oQjI5MOXQ3
Note : Above given code will print random (different) password everytime, for the size provided.
Code #2 :
Say if you want to generate random password, but from the set of given string. Let’s see how can we do this using ascii_letters :
import random
import string
def rand_pass(size, scope = string.ascii_letters + string.digits):
generate_pass = ''.join([random.choice(scope)
for n in range (size)])
return generate_pass
password = rand_pass( 10 , 'Geeks3F0rgeeKs' )
print (password)
|
Output :
kg3g03keG3
Please Login to comment...