小编Mik*_*ker的帖子

打印行的最短代码以['a','b']开头,以['y','z'结尾] Python 3

对于作业,我必须从以"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).

python startswith python-3.x ends-with

1
推荐指数
1
解决办法
488
查看次数

标签 统计

ends-with ×1

python ×1

python-3.x ×1

startswith ×1