python中新增指定位數的字母數字組合字串

2022-08-24 04:39:11 字數 1833 閱讀 6343

隨機字串

import

random

class

test():

deffunction(self):

list = [chr(i) for i in range(65,91)] + [chr(i) for i in range(97,123)] + [ str(i) for i in range(10)] + ['

.','

-','

~','

_'] #

大寫字母+小寫字母+數字 +特殊字元.-_~

#list顯示結果:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

'.', '-', '~', '_']

num = random.sample(list,32) #

輸出32個固定長度的組合字元

str1=''

value = str1.join(num) #

將取出的32個隨機數進行重新合併

print

(value)

#這裡定義了類和方法,如果只要功能,直接取方法裡的內容即可

a =test()

a.function()

執行結果:

>>vmsearqfh9xz852dd0cx_jgty7z~qipt

import

random

list = [chr(i) for i in range(65,91)] + [chr(i) for i in range(97,123)] + [ str(i) for i in range(10)] + ['

.','

-','

~','

_'] #

大寫字母+小寫字母+數字 +特殊字元.-_~

num = random.sample(list,10) #

輸出10個固定長度的組合字元

str1=''

value = str1.join(num) #

將取出的十個隨機數進行重新合併

ifnot

value[0].isdigit():

print (value)

import

random

defstrgen(num):

list1= [chr(i) for i in range(65,91)] + [chr(i) for i in range(97,123)] + [ str(i) for i in range(10)] + ['

.','

-','

~','_'

] value=""

for i in

range(num):

value = value + list1[random.randint(0, len(list1)-1)]

return

value

strgen(random.randint(1,100)) #

隨機取[1,100]之間的數字

Python保留指定位數的小數

f 1.23456 print 4f f print 3f f print 2f f 結果 1.2346 1.235 1.23 這個方法會進行四捨五入 print format 1.23456 2f print format 1.23456 3f print format 1.23456 4f 1....

生成指定位數的隨機數

輸入 要生成的隨機數的位數 輸出 隨機數 因為是32位系統,因此只能生成9位長度的10進製數。如果是10位的話可能會出現負數。溢位。c sharp view plain copy print?include include include include long myrand intn if n ...

js精確到指定位數的小數

將數字四捨五入到指定的小數字數。使用math.round 和模板字面量將數字四捨五入為指定的小數字數。省略第二個引數decimals,數字將被四捨五入到乙個整數。const round n,decimals 0 number e e round 3.1415926535897932384626433...