【问题标题】:arithmetic [MINUS] on string in pythonpython中字符串的算术[MINUS]
【发布时间】:2019-11-18 09:33:39
【问题描述】:

我有一个字符串,它基本上是一个 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)

【问题讨论】:

  • 您需要将月份存储在 int 变量中并减去 1,直到达到 0(条件)并继续将结果添加到列表中。

标签: python


【解决方案1】:

使用正则表达式。

例如:

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

【讨论】:

  • 感谢您写下答案,它也解决了我的问题,我会看看哪个更易于使用和管理以备将来使用,以及哪个我更了解:)
【解决方案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)

【讨论】:

  • 感谢您的回复只是想知道我应该如何阅读我刚接触 python 的这段代码并想学习这些转换以供我将来使用:)
  • 不客气,先生。你的意思是你想解释一下脚本行吗?
  • 是的,如果有可能我也收到错误 TypeError: expected string or bytes-like object got the error need to convert the variable into STR
  • 当我更改日期以将月份反映为 01 然后它创建的第二个元素为“000”时,该代码中似乎存在错误,应该是“012”
  • 还有一件事#获取最大的数字,在你的情况下,大部分时间将是日期我需要从标题中的第一个日期字符串而不是最大数字中获取月份所以我们不能在这里做这个假设
猜你喜欢
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多