对于作业,我必须从以"W"和"Z"开头并以"n"和"t"结尾的文本中打印行(所以Wn,Wt,Zn,Zt组合).我现在有一个代码可行,但似乎有点长,我想知道是否有办法缩短它?
这是代码:
import sys
def main():
for line in sys.stdin:
line = line.rstrip()
if line.startswith("W") and line.endswith("n"):
print(line)
if line.startswith("W") and line.endswith("t"):
print(line)
if line.startswith("Z") and line.endswith("n"):
print(line)
if line.startswith("Z") and line.endswith("t"):
print(line)
main()
Run Code Online (Sandbox Code Playgroud)
正如我所说,它有效,但似乎有点复杂.有关如何缩短的任何提示?
我试过line.startswith("Z","W"),line.endswith("t","n")但我得到一个类型错误(所有切片索引必须是整数或无或有一个__index__method).