首页 > 解决方案 > 无法在 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'

标签: python

解决方案


在您的string.py模块中似乎有以下代码:

print ("I said: %r.") % x

评估如下:

  1. print("I said: %r.")被执行,这会产生值None(因为print不返回任何东西)。

  2. 这个值(即None)被插入到上面的表达式中,因此None % x被评估。这会导致您看到错误消息。

看来你打算写:

print("I said: %r." % x)

即,首先插入x字符串,然后打印。


推荐阅读