# Python 随机字符串

**URL:** <https://www.isharkfly.com/t/python/13398>\
**Category:** Python\
**Tags:** python\
**Created:** [March 19, 2021, 1:39pm UTC](https://www.isharkfly.com/t/python/13398 "2021-03-19T13:39:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 19, 2021, 1:39pm UTC](https://www.isharkfly.com/t/python/13398/1 "2021-03-19T13:39:12Z")

</div>

在很多时候我们可能需要生成一些随机字符串。

Python 也为我们提供了生成随机字符串的方法和函数。

这个函数是在 random 库中定义的函数 choice。

通常 choice 将会从给定的字符串中挑选一个。

根据 Python 官方在 string.py 中有关字符串的定义。

```auto
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace

```

上面的字符串是可以供你随时使用的 ascii 字符串。

当调用方法 `choice(string.ascii_uppercase)` 的意思是将会随机从大写字符中挑选出一个字符。

如果我们希望要有 6 个长度的随机字符串，应该怎么办呢？

我们应该需要将上面的函数执行 6 次，然后将 6 次执行的结果拼接起来即可。

比如，我们可以这样写：

`"".join([choice(printable) for x in range(int(length))])`

length 是我们希望拼接的字符串的长度。  
printable 是可以用于生成字符串的字符。

![python-string-01](https://www.isharkfly.com/images/transparent.png)

如上面图中我们代码运行的结构就是用于测试随机字符串生成的。
