对于作业,我必须打印文本中以“W”和“Z”开头并以“n”和“t”结尾的行(所以 W-n、W-t、Z-n、Z-t 组合)。我现在有一个可以使用的代码,但它似乎有点长,我想知道是否有办法缩短它?
这是代码:
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()
正如我所说,它有效,但似乎有点复杂。关于如何缩短的任何提示?
我尝试了 line.startswith("Z","W") 和 line.endswith("t","n") 但我遇到了类型错误(所有切片索引必须是整数或 None 或具有 __index__ 方法)。
请您参考如下方法:
你可以这样做:
line = line.rstrip()
if line and line[0] in "WZ" and line[-1] in "nt":
print(line)
或者使用正则表达式:
import re
# ...
if re.match(r'^[WZ].*[nt]$', line):
print(line)
# ^ beginning of string
# $ end of string
# [WX] matches W or X
# .* any character 0 or more times
