[英]Checking if string element is present in a list with Python?
I have the following piece of code: 我有以下代码:
self.ignore_dir_extensions = ['xcodeproj']
item = repr(extension.split('/')[0])
print "String: " + item
if item in self.ignore_dir_extensions:
print "Available: " + item
Let's say I have this output: 假设我有以下输出:
String: 'xcodeproj'
Expected output: 预期产量:
String: 'xcodeproj'
Available: 'xcodeproj'
Could anyone help me out here? 有人可以帮我吗?
Try the following: 请尝试以下操作:
self.ignore_dir_extensions = ['xcodeproj']
item = extension.split('/')[0]
print "String: " + repr(item)
if item in self.ignore_dir_extensions:
print "Available: " + repr(item)
You do not want to have item
be the result of repr()
, because repr()
on a string will add quotes, for example: 您不希望
item
是repr()
的结果,因为字符串上的repr()
会添加引号,例如:
>>> repr("xcodeproj")
"'xcodeproj'"
>>> print repr("xcodeproj")
'xcodeproj'
>>> print "xcodeproj"
xcodeproj
When you are checking to see if the string exists in the list, you don't want the quotes unless the string you are trying to match also has them. 当您检查列表中是否存在该字符串时,除非您尝试匹配的字符串也包含引号,否则您不希望使用引号。
Your test for is-string-contained-in-list is correct. 您对is-string-contain-in-list的测试是正确的。 However, you are testing for the presence of a different string than you intended.
但是,您正在测试是否存在与预期不同的字符串。 You called repr on your string, so the name item is bound to the string
"'xcodeproj'"
(not to the string "xcodeproj"
). 您在字符串上调用了repr,因此名称项绑定到字符串
"'xcodeproj'"
(而不是字符串"xcodeproj"
)。
I would personally do this: 我个人会这样做:
self.ignore_dir_extensions = ['xcodeproj']
item = repr(extension.split('/')[0])
print "String: " + item
try:
self.ignore_dir_extensions.index(item)
print "Available: " + item
except:
pass
you can simply use: 您可以简单地使用:
item = extension.split('/')[0]
print "String: '%s'" % item
if item in self.ignore_dir_extensions:
print "Available: '%s'" %` item
this way you avoid the problems with repr 这样您可以避免repr的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.