首页 > 解决方案 > 在特定子字符串之后打印所有内容

问题描述

我正在尝试在日期时间字符串之后打印内容。就像今天的日期 09-04-2019(mm-dd-yy) 我想在 09042019 字符串开始时打印所有内容。在此之前它不会打印任何内容。我格式化了日期根据字符串。但在该日期子字符串之后无法打印。这是我到目前为止所做的:

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
date_time = now.strftime("%m%d%Y")
d=str(date_time)
print(d)
content='''(1115 09032019) Arafat hello
(1116 09032019) Arafat a
(1116 09032019) Arafat b
(1117 09032019) space w
(1117 09042019) space a
(1117 09042019) space a'''
print(content)

body=content[:content.find(d)]

我希望 09042019 启动时的输出是这样的

(1117 09042019) space a
(1117 09042019) space a

标签: pythonsplitsubstring

解决方案


如果我理解正确,您想打印以包含变量的行开头的所有内容d。如果是这种情况,下面的代码应该做你想做的事:

import itertools

content='''(1115 09032019) Arafat hello
(1116 09032019) Arafat a
(1116 09032019) Arafat b
(1117 09032019) space w
(1117 09042019) space a
(1117 09042019) space a'''
d = '09042019' # Hardcoded for testing

# Skip (drop) all the lines until we see 'd'
lines = iter(content.splitlines())
lines = itertools.dropwhile(lambda line: d not in line, lines)

# Print the rest of the lines
for line in lines:
    print(line)

笔记

  • itertools.dropwhile跳过行,直到它d第一次遇到包含变量的行。
  • 之后,只需打印出其余的行,我们就完成了

推荐阅读