📜  Python字符串|十六进制数

📅  最后修改于: 2022-05-13 01:55:15.168000             🧑  作者: Mango

Python字符串|十六进制数

在 Python3 中, string.hexdigits是一个预初始化的字符串,用作字符串常量。在Python中, string.hexdigits将给出十六进制字母“0123456789abcdefABCDEF”。

注意:确保导入字符串库函数以使用字符串.hexdigits

代码#1:

# import string library function 
import string 
    
# Storing the value in variable result 
result = string.hexdigits 
    
# Printing the value 
print(result) 

输出 :

0123456789abcdefABCDEF

代码#2:给定代码检查字符串输入是否只有十六进制数字字母

# importing string library function 
import string 
     
# Function checks if input string 
# has only hexdigits or not 
def check(value): 
    for letter in value: 
             
        # If anything other than hexdigit 
        # letter is present, then return 
        # False, else return True 
        if letter not in string.hexdigits: 
            return False
    return True
     
# Driver Code 
input1 = "0123456789abcdef"
print(input1, "--> ",  check(input1)) 
     
input2 = "abcdefABCDEF"
print(input2, "--> ", check(input2)) 
     
input3 = "abcdefghGEEK"
print(input3, "--> ", check(input3)) 

输出:

0123456789abcdef -->  True
abcdefABCDEF -->  True
abcdefghGEEK -->  False

应用:
字符串常量hexdigits可用于许多实际应用。让我们看一段代码,解释如何使用数字生成给定大小的强随机密码。

# Importing random to generate 
# random string sequence 
import random 
    
# Importing string library function 
import string 
    
def rand_pass(size): 
        
    # Takes random choices from 
    # string.hexdigits 
    generate_pass = ''.join([random.choice(string.hexdigits) 
                        for n in range(size)]) 
                            
    return generate_pass 
    
# Driver Code  
password = rand_pass(10) 
print(password)  

输出:

e497FEe2bC