因此,我希望每次调用
时生成一个随机的十六进制值randhex = "\\x" + str(random.choice("123456789ABCDEF")) + str(random.choice("123456789ABCDEF"))
到目前为止,我所提出的只是做出不同的=调用(例如randhex1 = ^^,randhex2)等等,但这样做既乏味又低效,我不想这样做
ErrorClass = "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF"))
因为这看起来并不好,很难说有多少。
我正在尝试将其分配给此
ErrorClass = randhex1 + randhex2 + randhex3 + randhex4,
Flags = randhex5,
Flags2 = randhex6 + randhex7,
PIDHigh = randhex2 + randhex5,
理想情况下,我不希望分配不同的数字,而是希望它们都是统一的,或者像ErrorClass = randhex * 4那样干净。但是,如果我这样做,它只是将代码复制为如下所示:
Input: ErrorClass = randhex + randhex + randhex + randhex
Output: \xFF\xFF\xFF\xFF
显然不起作用,因为它们完全相同。任何帮助都会很棒。
答案 0 :(得分:2)
创建一个返回随机生成的字符串的函数。每次打电话都会给你一个新的价值。
import random
def randhex():
return "\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF"))
ErrorClass = randhex() + randhex() + randhex() + randhex()
Flags = randhex()
Flags2 = randhex() + randhex()
PIDHigh = randhex() + randhex()
print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)
示例结果:
\xBF\x2D\xA2\xC2
\x74
\x55\x34
\xB6\xF5
为了更加方便,请向size
添加randhex
参数,这样您就不必每次分配多次调用它:
import random
def randhex(size=1):
result = []
for i in range(size):
result.append("\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF")))
return "".join(result)
ErrorClass = randhex(4)
Flags = randhex()
Flags2 = randhex(2)
PIDHigh = randhex(2)
print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)