在破折号后更改字符串结尾

2024-09-30 05:17:36 发布

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

我有一个string格式的"12345-0012-0123",我想把它们都改成12345-0012-123"格式,这样破折号后面的最后一部分就只有三位数而不是四位数了。你知道吗

在所有情况下,破折号后面的最后一部分最多只有三个实数,我需要在0001、0012、0123前面加一个零。。。你知道吗

一些字符串,我将编辑已经在正确的格式,所以快速检查,看看我甚至需要执行更正将更好。。。你知道吗

编辑:已解决!!你知道吗

对于任何一个感兴趣的人来说,这是我正在使用的ArcGIS计算器代码,它是由anirudh提供的答案修改而来的。。。你知道吗

#Convert to three digit count def FixCount(s): length = len(s[s.rfind('-')+1:]) if length > 3: return s.rstrip(s[s.rfind('-')+1:])+s[s.rfind('-')+2:] else: return s.rstrip(s[s.rfind('-')+1:])+s[s.rfind('-')+1:] __esri_field_calculator_splitter__ FixCount(str( !input_field_id! ))


Tags: 字符串编辑fieldstringreturn格式情况length
3条回答

这是regular expressions的工作!你知道吗

给出:

>>> s
'12345-0012-0123'

我们要匹配两组:

  • 一个或多个(+)数字(d),后跟一个-,后跟一个或多个(+)数字(d),后跟一个-
  • 然后有一个或多个(+0,我们没有捕获(没有())。如果只想匹配单个0,请删除+!你知道吗
  • 一个或多个(+)数字(d

然后我们要替换(^{})我们的字符串s,它将这个正则表达式与那些capture groups中的内容匹配。你知道吗

>>> re.sub('(\d+-\d+-)0+(\d+)', r'\1\2', s)
'12345-0012-123'

注意:

^{}返回修改后的s,它不会就地修改它。你知道吗

这不一定是正则表达式的工作!你知道吗

def reformat(a):
    x = a.split("-")
    x[-1] = "%03d"%int(x[-1])
    return "-".join(x)

示例用法:

In [14]: reformat("12345-0012-0001")
Out[14]: '12345-0012-001'

因此,在这里给出一些其他答案:

In [55]: %timeit v[:len(v)-4]+str(int(v.split('-')[2]))
100000 loops, best of 3: 1.83 us per loop

In [56]: %timeit reformat(v)
100000 loops, best of 3: 1.99 us per loop

In [57]: %timeit re.sub('(\d+-\d+-)0+(\d+)', r'\1\2', x)
100000 loops, best of 3: 9.53 us per loop

正则表达式在这里是过度杀伤力的,而且与仅仅使用内置表达式相比速度很慢。你知道吗

你可以像johnsyweb所说的那样使用regex,如果你不想使用regex,也可以使用下面的。你知道吗

s = "12345-0012-0123"
length = len(s[s.rfind('-')+1:])
if length > 3:
    print s.rstrip(s[s.rfind('-')+1:])+s[s.rfind('-')+2:]
else:
    print s.rstrip(s[s.rfind('-')+1:])+s[s.rfind('-')+1:]

相关问题 更多 >

    热门问题