python - 在特定子字符串之后打印所有内容
问题描述
我正在尝试在日期时间字符串之后打印内容。就像今天的日期 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
解决方案
如果我理解正确,您想打印以包含变量的行开头的所有内容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
第一次遇到包含变量的行。 - 之后,只需打印出其余的行,我们就完成了
推荐阅读
- git - 更改密码,无法推送到私有存储库
- arduino - 在 HC-05 传感器上创建配对限制
- git - 修复提交树以再次默认快进
- vala - 错误:返回值转移所有权,但方法返回类型尚未声明转移所有权
- wordpress - 将更多产品从联系表 7 添加到 woocommerce 结帐
- apache - 访问 JCas 注释列表
- firebase - 在颤动中获取用户数据到firestore?
- sql - 在 postgresql 中添加由 id 引用链接的单元序列
- spring-boot - 无法使用其他角色进行操作,然后是超级用户
- node.js - Node JS - 在promise-ftp上没有管道无法获取流数据