python - 使用字符串读取列表并将其转换为int()但保留特定格式

问题描述 投票:1回答:4

我有一个充满字符串的文件,我将其读入列表。现在我想通过查找... / 002 / ...找到一个特定的行(例如下面的第一行)并添加到这些002 +5给我/ 007 /,以便找到我的下一行包含/ 007 /的行。

该文件看起来像这样

https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1345.006.2018003152137.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1345.006.2018005220045.hdf

有了这个我可以识别例如第一行:

match = re.findall("/(\d{3})/", data_time_filtered[i])

现在的问题是:如何将字符串转换为整数但保持格式00X?这是Ansatz的正确吗?:

match_conv = ["{WHAT's in HERE?}".format(int(i)) for i in match]

编辑根据以下建议的答案:

显然,没有办法直接读取字符串中的数字并保持它们原样?

使用zfill和其他建议函数向数字添加0会使其更复杂,因为/ 00x /应保持最多3位数(因为它们代表一年中的几天)。所以我一直在寻找一种有效的方法来保持字符串中的数字,并使它们“可数学”。

python formatting
4个回答
1
投票

我们可以先定义一个函数,它将一个整数添加到字符串中并返回一个字符串,用零填充以保持相同的长度:

def add_to_string(s, n):
    total = int(s)+n
    return '{:0{}}'.format(total, len(s))

add_to_string('003', 2)
#'005'
add_to_string('00030', 12 )
#'00042

然后我们可以使用带有替换功能的re.sub。我们使用匹配一组3位数的正则表达式r"(?<=/)\d{3}(?=/)",前面和后面是/,不包括在匹配中。

替换函数将匹配作为参数,并返回一个字符串。您可以对其进行硬编码,如下所示:

import re

def add_5_and_replace(match):
    return add_to_string(match.group(0), 5)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", add_5_and_replace, url)
print(new)
# https://nasa.gov/archive/allData/6/MYD021KM/2018/007/MYD021KM.hdf

但是将值传递给添加可能会更好。使用lambda:

def add_and_replace(match, n=1):
    return add_to_string(match.group(0), n)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", lambda m: add_and_replace(m, n=5), url)

或部分功能。那么完整的解决方案可能是:

import re
from functools import partial

def add_to_string(s, n):
    total = int(s)+n
    return '{:0{}}'.format(total, len(s))

def add_and_replace(match, n=1):
    return add_to_string(match.group(0), n)

url = 'https://nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.hdf'

new = re.sub(r"(?<=/)\d{3}(?=/)", partial(add_and_replace, n=3), url)
print(new)

# https://nasa.gov/archive/allData/6/MYD021KM/2018/005/MYD021KM.hdf

如果您只想将默认值1添加到您的号码,您可以简单地写

new = re.sub(r"(?<=/)\d{3}(?=/)", add_and_replace, url)
print(new)

# https://nasa.gov/archive/allData/6/MYD021KM/2018/003/MYD021KM.hdf

1
投票

了解mini format language here

c = "{:03}".format(25) # format a number to 3 digits, fill with 0
print(c)

输出:

025

1
投票

你不能让int成为001002。他们只能是12

您可以使用字符串执行类似操作。

>>> "3".zfill(3)
'003'
>>> "33".zfill(3)
'000ss'
>>> "33".rjust(3, '0')
'033'
>>> int('033')
33

>>> a = 3
>>> a.zfill(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'zfill'

1
投票

或者你rjustljust

>>> '2'.ljust(3,'0')
'200'
>>> '2'.rjust(3,'0')
'002'
>>> 

要么:

>>> '{0:03d}'.format(2)
'002'

要么:

>>> format(2, '03')
'002'

要么:

>>> "%03d" % 2
'002'
© www.soinside.com 2019 - 2024. All rights reserved.