简体   繁体   English

在字符串前打印10个字符

[英]Print 10 characters before a string

I'm currently trying to print a string that usually comes before another string, for example "12/07/201911 : 00Type of Occurrence" . 我当前正在尝试打印通常在另一个字符串之前的字符串,例如"12/07/201911 : 00Type of Occurrence" Here I'm trying to print the time "11 : 00" which always come before the text "Type of Occurrence" . 在这里,我尝试打印时间"11 : 00" ,该时间总是在文本"Type of Occurrence"

I have tried this which print everything before the identifier. 我已经尝试过在标识符之前打印所有内容。 I would like to only print 7 characters before the identifier. 我只想在标识符前打印7个字符。

import re
A="12/07/2019 11 : 00Type of Occurrence"
print(A.split('Type of Occurrence', 1)[0].replace('.', '').upper())

It prints : 它打印:

12/07/2019 11 : 00

Try this: 尝试这个:

A="12/07/2019 11 : 00Type of Occurrence"
print(" ".join(A.split("Type of Occurrence")[0].split()[1:]))

OUTPUT : 输出

11 : 00

Process : 工艺流程:

  1. A.split("Type of Occurrence")[0] gives "12/07/2019 11 : 00" A.split("Type of Occurrence")[0]给出"12/07/2019 11 : 00" A.split("Type of Occurrence")[0] "12/07/2019 11 : 00"

  2. "12/07/2019 11 : 00".split()[1:] gives ['11', ':', '00'] "12/07/2019 11 : 00".split()[1:]给出['11', ':', '00']

  3. " ".join(['11', ':', '00']) gives 11 : 00 " ".join(['11', ':', '00'])给出11 : 00

Try this : 尝试这个 :

>>> A="12/07/2019 11 : 00Type of Occurrence"
>>> i = A.find('Type of Occurrence')
>>> i
18
>>> A[i-7:i]
'11 : 00'

If the whitespaces between the colon can vary, you might use a capturing group for the time part and match Type of Occurrence: 如果冒号之间的空格可能有所不同,则可以在时间部分使用捕获组并匹配发生类型:

((?:0[0-9]|1[0-9]|2[0-3])\s*:\s*[0-5][0-9])Type of Occurrence

Regex demo 正则表达式演示

Basic Idea: 基本思路:

A="12/07/2019 11 : 00Type of Occurrence"

A = A.split('Type of Occurrence', 1)[0].replace('.', '').upper()
A[-7:]
>>> '11 : 00'

Is this what you want? 这是你想要的吗?

I would like to only print 7 characters before the identifier. 我只想在标识符前打印7个字符。

You may use this regex: 您可以使用此正则表达式:

>>> import re
>>> A="12/07/2019 11 : 00Type of Occurrence"
>>> print re.findall(r'(.{7})Type of Occurrence', A)[0]
11 : 00

re.findall prints captured group if they are available in regex. re.findall打印捕获的组(如果正则表达式中可用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM