【问题标题】:adding numbers to string representations of numbers in python [duplicate]在python中将数字添加到数字的字符串表示中[重复]
【发布时间】:2017-11-16 16:59:41
【问题描述】:

我正在处理格式为“000351”的字符串。将它们视为里程表读数。我想增加它们。例如 我想将 1 加到 '000345' 并得到 '000346'。

以下 python 代码可以完成这项工作,但看起来相当繁琐。有没有更优雅的方法来做到这一点?

s='000345'
t=int(s)
t=t+1
int_to_6digit_string(t)

其中函数int_to_6digit_string()如下

def int_to_6digit_string(i):
    if i<0 or i>999999:
        return 'argument out of bounds'
    j=str(i)
    if len(j) == 1:
        return '00000'+j
    elif len(j) == 2:
        return '0000'+j
    elif len(j) == 3:
        return '000'+j
    elif len(j) == 4:
        return '00'+j
    elif len(j) == 5:
        return '0'+j
    else:
        return j

【问题讨论】:

  • 这个最好提交给codereview.stackexchange.com
  • 溢出时会发生什么(s 正好是 999999)?您是否考虑过改用str.format()
  • 你可以使用 zfill() 函数。
  • Lots of ways 用 0 填充数字。
  • 包括我回答的内容

标签: python string integer data-conversion


【解决方案1】:

使用字符串格式:'{:06}'.format(your_number)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多