1

作为这个原始问题的后续: Python: Stripping elements of a string array based on the first character of each element

我想知道是否可以扩展此 if 语句:

with open(bom_filename, 'r') as my_file:
    file_array = [word.strip() for word in my_file if word.startswith("/")]

包括和第二个条件:

with open(bom_filename, 'r') as my_file:
    file_array = [word.strip() for word in my_file if (word.startswith("/")) & not(word.endswith("/"))]

这会产生语法错误,但我希望可以使用一些替代语法!

4

1 回答 1

1
with open(bom_filename, 'r') as my_file:
    file_array = [word.strip() for word in my_file if (word.startswith("/") and not(word.strip().endswith("/")))]

你需要改变

if (word.startswith("/")) & not(word.endswith("/"))

if (word.startswith("/") and not(word.strip().endswith("/"))) 

或删除额外的括号:(根据@viraptor的建议)

if word.startswith("/") and not word.strip().endswith("/") 

注意if(...)...必须包含所有的逻辑而不仅仅是if(word.startswith("/"))。并将其替换&为按位运算符and

于 2013-05-14T13:39:00.707 回答