python - 无法在 python 3 中导入字符串
问题描述
import random
import string
def pw_gen(size = 8, chars = string.ascii_letters + string.digits + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
print(pw_gen(int(input('How many characters in your password'))))
我正在尝试运行此代码,但在导入时string
,我收到此错误:
There are 10 types of people.
Those who know binary and those who don't.
I said: %r.
Traceback (most recent call last):
File "passgen1.py", line 3, in <module>
import string
File "D:\python\string.py", line 9, in <module>
print ("I said: %r.") % x
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
解决方案
在您的string.py
模块中似乎有以下代码:
print ("I said: %r.") % x
评估如下:
print("I said: %r.")
被执行,这会产生值None
(因为print
不返回任何东西)。这个值(即
None
)被插入到上面的表达式中,因此None % x
被评估。这会导致您看到错误消息。
看来你打算写:
print("I said: %r." % x)
即,首先插入x
字符串,然后打印。
推荐阅读
- java - 如何计算 2 的 N 次方,其中 N 是一个非常大的数字
- node.js - 如何在运行 gulp build 命令时修复未关闭的块 SCSS 错误
- reactjs - 我无法使用纱线构建它
- python - 如何在脚本运行时将更多项目添加到多处理队列
- google-apps-script - 如何将 Range[ ] 转换为整数/类值?
- contiki - 如何向自己发送 runicast 消息?
- javascript - 将线性渐变与动态背景图像相结合
- c# - Roslyn Analyzer - 访问 ITextBuffer
- ios - 是否可以在 Linux 上运行 Azure 管道代理来构建 iOS 应用程序?
- react-native - 尝试使用 eval() 函数设置状态(React Native)