【问题标题】:print everything after specific substring在特定子字符串之后打印所有内容
【发布时间】:2020-01-06 16:42:39
【问题描述】:

我正在尝试在日期时间字符串之后打印内容。就像今天的日期 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

【问题讨论】:

  • 不完全确定您要在这里做什么,但乍一看,这看起来像是自定义日志格式化程序的用途;参见例如docs.python.org/3/howto/…
  • 你确定你的输出吗?为什么第一行重复?

标签: python split substring


【解决方案1】:

如果我理解正确,您想打印从包含变量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 的行。
  • 之后,只需打印出其余的行,我们就完成了

【讨论】:

    【解决方案2】:

    我的尝试:

    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 09022019) Arafat hello
    (1116 09022019) Arafat a
    (1116 09032019) Arafat b
    (1117 09032019) space w
    (1117 09042019) space a
    (1117 09042019) space a'''
    print(content)
    
    print('-- result --')
    # find d
    d_pos = content.find(d)
    # find where the line containing d starts
    d_pos_fullline = content.rfind('\n', 0, d_pos) + 1
    body=content[d_pos_fullline:]
    print(body)
    

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多