【问题标题】:Python 2.7, add a dash before the last two digits of a stringPython 2.7,在字符串的最后两位数字前添加破折号
【发布时间】:2015-08-18 16:04:45
【问题描述】:

使用 Python 2.7,我想在字符串的最后两位数字之前添加一个破折号,前提是字符串都是数字。

例如:

1234567 变成 12345-78

12345TT 没有变化

12345PP678 没有变化

ABCDEFGH 没有变化

【问题讨论】:

  • 奇迹1234567 becomes 12345-78,怎么样?

标签: python string python-2.7


【解决方案1】:

您不需要正则表达式来查看字符串是否全为数字,您可以使用str.isdigit,如果全为数字,则切片并添加“-”,如果不是保持原样:

s = "1234578"

s ="{}-{}".format(s[:-2],s[-2:]) if s.isdigit() else s
print(s)
12345-78

它也比使用正则表达式更有效。

In [16]: s = "1234578" * 1000

In [17]: r= re.compile(r'^(\d*)(\d{2})$')

In [18]: timeit r.sub(r'\1-\2',s)
1000 loops, best of 3: 459 µs per loop

In [19]: timeit "{}-{}".format(s[:-2],s[-2:]) if s.isdigit() else s
10000 loops, best of 3: 20.7 µs per loop

【讨论】:

    【解决方案2】:

    我认为1234567 会变成12345-67

    re.sub(r'^(\d*)(\d{2})$', r'\1-\2', s)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2021-09-01
      相关资源
      最近更新 更多