python中字符串的算术[MINUS]

2024-03-29 14:40:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,它基本上是一个CSV文件的头,我必须从中提取月份,然后通过在它前面附加一个“0”来将它转换为一个字符串,以便与其他值进行比较。你知道吗

标题--

HGLOABCD8PSGL_ZXFH J20190603NXT_APAC

从这里,我需要从20190603(06)中提取月份,然后创建一个类似['006','005']的列表,列表的第二个元素将是标题中给定月份的前一个月

另外,标题也可以是月份不同的地方

HGLOABCD8PSGL_ZXFH J20191003NXT_APAC

我已经为第一个元素写了这样的东西,但不确定如何减去一个月,然后在其中附加“0”。你知道吗

acc_period = []
acc_period.append('0'+str(header)[26:28])

acc_period.append(int('0') + int(str(header)[26:28])-1)
print (acc_period)

Tags: csv字符串元素标题列表periodintheader
2条回答

尝试正则表达式:

import re

output = list()
header = 'HGLOABCD8PSGL_ZXFH J20190103NXT_APAC'
#Using the regex pattern '\d*' this will fnid all the numeric sequences in the input string
find_all_numbers = re.findall('\d*', header)

#Filtering out any empty string resulted from extraction
numbers = [num for num in find_all_numbers if len(num)==8]

#Getting the largest number which is most of the time going to be the date in your case
date = numbers[0]

#Unpacking the data using string slicing

year, month, day = date[:4], date[4:6], date[6:]

#Using string format defining the desired format using left 0 padding
current_month, previous_month = '{0:03d}'.format(int(month)), '{0:03d}'.format(int(month)-1)
if previous_month =='000':
    previous_month = '012'
output.extend((current_month, previous_month))
print(output)

使用正则表达式。你知道吗

例如:

import re
from datetime import datetime, timedelta
data = ['HGLOABCD8PSGL_ZXFH J20190603NXT_APAC', 'HGLOABCD8PSGL_ZXFH J20191003NXT_APAC', 'HGLOABCD8PSGL_ZXFH J20190103NXT_APAC']

def a_day_in_previous_month(dt):   #https://stackoverflow.com/a/7153449/532312
    return (dt.replace(day=1) - timedelta(days=1)).month

for i in data:
    m = re.search(r"(\d{8,})", i)
    if m:
        date = datetime.strptime(m.group(0), "%Y%m%d")
        print("{}".format(date.month).zfill(3), "{}".format(a_day_in_previous_month(date)).zfill(3))

输出:

006 005
010 009
001 012

相关问题 更多 >