我试图让用户输入 10 个名字并将它们放入一个列表中并删除该列表中的偶数单词
name1 = str (input("Please Enter a Name:"))
lista = []
lista.append(name1)
if name1 % 2 == 0:
lista.remove(name1)
这是我的代码搞乱的部分,它显示“TypeError:并非所有参数在字符串格式化期间都被转换”
name1 = str (input("Please Enter a Name:"))
lista = []
lista.append(name1)
if name1 % 2 == 0:
lista.remove(name1)
This is the part where my code messes up it says " TypeError: not all arguments converted during string formatting"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例输入: ab cc d gg e ggg ff
输出: ['a', 'b', 'd', 'e', 'ggg']
但是,通过检查提供的输入的长度,这可以更加简化提供了它,并且仅添加奇数长度的单词。为您节省一个循环。这是代码:
Example input: a b cc d gg e ggg ff
Output: ['a', 'b', 'd', 'e', 'ggg']
However, this could be even more simplified, by checking the length of provided input as it's provided, and adding only odd-length words instead. Saves you one loop. Here's the code:
这里的错误是
%
str
上的操作员用于格式化;向操作员的参数(右侧的所有内容)需要与字符串中的格式化指令相对应。您正在尝试将其用作int
模量运算符,因为它是str
。如果您的目的是根据字符串的 length 奇数,甚至使用
len()
函数,请注意:请注意,请注意:请注意,请注意:请注意您无需将
input()
的结果转换为str
,并且您只需使用len(n)%2
查看len(n)
是否奇怪(因为1是true,而0为false)。使用Python的当前版本合理的版本,您可以在一个简单的列表理解中完成这一切:
The error here is that the
%
operator on astr
is for formatting; the arguments to the operator (everything to the right of it) need to correspond to formatting directives inside the string. You're trying to use it as theint
modulus operator, which doesn't work because it's astr
.If your intent is to filter based on whether the length of the string is odd or even, use the
len()
function on the string, as others have suggested:Note that you don't need to convert the result of
input()
to astr
, and that you can simply uselen(n) % 2
to see iflen(n)
is odd (because 1 is true and 0 is false).With a reasonably current version of Python you can do this all in a single easy list comprehension: