python生成8位隨機字元串的方法分析

Python生成8位隨機字元串的方法分析
篇文章主要介紹了Python生成8位隨機字元串的方法,結合實例形式對比分析了2種比較常用的隨機字元串生成技巧,具有一定參考借鑒價值,需要的朋友可以參考下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string
#第一種方法
seed = "!@#$%^&*()_+=-"
sa = []
for i in range(8):
sa.append(random.choice(seed))
salt = '.join(sa)
print salt
#運行結果:l7VSbNEG
#第二種方法
salt = '.join(random.sample(string.ascii_letters + string.digits, 8))
print salt
#運行結果:VOuCtHZs

生成隨機字元串

在加密用戶密碼的時候,一個好方法就是產生一個隨機字元串,然後再和密碼進行混合求摘要。產生隨機字元串的方法找到了這些。

第一種比較簡單,易於理解

第二種不好理解,但很簡潔

本來我只想隨機取四個數字的,用的random.randint(1000,9999)。但是這個開頭不會出現0,有點不爽,後來找到這個文章。

② 如何用Python語言生成隨機字元串

你的意思是生成的隨機字元串過濾指定的子串吧。 首先你那個函數可以簡化成: from random import samplestr = ''.join(sample('', 8))print str然後過濾AA和Ab,最簡單的方法就是

③ python 生成隨機字元串

def getstr(n):
st = ''
while len(st) < n:
temp = chr(97+random.randint(0,25))
if st.find(temp) == -1 :
st = st.join(['',temp])
return st

④ 怎麼用python隨機生成一系列字元串

用Python隨機生成字元串:

fromrandomimportRandom
defrandom_str(randomlength=8)://固定長度8
str=''//str初始為空
chars=''
length=len(chars)-1
random=Random()//random模塊用於生成隨機數版
foriinrange(randomlength)://循環生成隨機字元串權
str+=chars[random.randint(0,length)]
returnstr

⑤ 新手求助:怎麼用python隨機生成一系列字元串

from random import Random
def random_str(randomlength=8): //固定長度來8
str = '' //str初始為空自
chars = ''
length = len(chars) - 1
random = Random() //random模塊用於生成隨機數
for i in range(randomlength): //循環生成隨機字元串
str+=chars[random.randint(0, length)]
return str

⑥ Python中怎麼隨機輸出一個字元串

importrandom
ret=random.randint(0,3)

這樣就可以得到[0, 3]中的隨機數了。

⑦ python 生成長度為100的字元串,值全為1

'1' * 100

⑧ 用python生成一個向量,每個元素都是同一個字元串。

使用python的列表生成式即可,列表生成式即List
Comprehensions,是Python內置的非常簡單卻強大的可以用來創建list的生成式。代碼如下:<pre
t="code"
l="python">>>>
nl
=
[i
+
1
for
i
in
range(1,
10)]
>>>
nl
[2,
3,
4,
5,
6,
7,
8,
9,
10]
>>>

⑨ python中怎麼建立一個字元串列表

可以使用字元串的join方法,可以把列表的各個元素連接起來,字元串就是連個列表各元素的連接符。

1
2
3
>>> l = ['I', 'want', 'a', 'apple', 'pi']
>>> ' '.join(l)
'I want a apple pi'
' '代表使用空格連接字元串的各個元素。

我們甚至可以使用空字元串來連接列表的各個元素,這樣連接後,列表的各個元素間將不會有間隔。

1
2
3
>>> l2 = ['1','2','3','4','5']
>>> ''.join(l2)
'12345'

⑩ python怎麼生成日期字元串

將時間轉換為字元串可以使用strftime方法from datetime import datetimed = datetime(year=2015, month=6, day=18) #初始化datetime類的時間d.strftime('%Y-%m-%d') #轉換成字元串