如何连接字符串和整数以获得三位数

时间:2016-03-17 09:38:22

标签: python string python-3.x int concatenation

我在初学者的课程中,我制作了这段代码,但它不起作用

def compressData(self, s):
    compressed = ''
    begin = 0
    blockSize = 1073741824 # 1Gb
    compressor = zlib.compressobj()
    while begin < len(s):
      compressed = compressed + compressor.compress(s[begin:begin + blockSize])
      begin = begin + blockSize
    compressed = compressed + compressor.flush()
    return compressed

最终输出需要看起来像:

random_number = str(random.randrange (1, 1000))
random_number_length = (len (random_number))
zero_number = ("0" * 3 - (random_number_length))
final_number = (random_number_length + random_number)
print (final_number)

而不是:

004

即使生成的数字是89或7,我也需要得到一个三位数。

当我尝试这个时,我得到错误:

4

我猜它与字符串和整数有关。

5 个答案:

答案 0 :(得分:5)

Python字符串有一个zfill方法,您可以使用该方法用前导零填充字符串。

>>> '1'.zfill(3)
'001'
>>> '89'.zfill(3)
'089'
>>> '189'.zfill(3)
'189'

不允许使用zfill:

>>> def f(n):
...     s = str(n)
...     return '0' * (3 - len(s)) + s
... 
>>> 
>>> for x in [1, 11, 111]: print(f(x))
... 
001
011
111

答案 1 :(得分:3)

作为zfill的替代方案,您可以使用rjust

>>> '1'.rjust(3, '0')
'001'
>>> '89'.rjust(3, '0')
'089'
>>> '189'.rjust(3, '0')
'189'

或格式化:

>>> "{:0>3}".format('1')
'001'
>>> "{:0>3}".format('89')
'089'
>>> "{:0>3}".format('189')
'189'

答案 2 :(得分:1)

    >>> '%03d' % 1
    '001'

答案 3 :(得分:1)

由于您出于教育原因这样做,答案是运营商(例如*,+, - 等)具有优先权。

你在写:

zero_number = ("0" * 3 - (random_number_length))

首先使用运算符*,然后使用运算符-

这才是真正发生的事情:

# assuming number is 89, so random_number_length is 2

zero_number = ("0" * 3 - (random_number_length))
zero_number = ("0" * 3 - (2))
zero_number = ("000" - (2))
zero_number = ("000" - 2)

# error - you can't subtract a number (an integer) from a string.

你需要在字符串乘法之前强制减法。

zero_number = "0" * (3 - random_number_length)

这是最终的代码,格式正确(我删除了不必要的括号,以及不必要的空格)

import random

random_number = str(random.randrange(1, 1000))
random_number_length = len(random_number)
zero_number = "0" * (3 - random_number_length)
final_number = zero_number + random_number
print(final_number)

您还在随机数中添加了错误的内容 - 您应该在(您的)第4行中添加“zero_number”变量,这是您在上一行(第3行)中创建的

答案 4 :(得分:0)

以上答案更有用(你不必重新发明轮子),但要使用你自己的代码:

INSERT INTO pictures (picID, taskID, ...) VALUES (NULL, 'arbitrary', ...);
//perform remaining operations related to task
//insert task into task table
UPDATE pictures SET taskID = $correcttaskid WHERE taskID = 'arbitrary';

尝试使用较少的括号:这些有时令人困惑。但是你的主要问题是:

import random

# Get the random number
random_number = str(random.randrange (1, 1000))

# Check number of digits in the number
random_number_length = len (random_number)

# Use the number of digits to get the number of zeros
zero_number = "0" * (3 - (random_number_length))

# Concatenate zero_number with random_number
final_number = zero_number + random_number

print (final_number)
# 006

乘法在减法之前出现,所以它是:

  1. zero_number = ("0" * 3 - (random_number_length)) =&gt;是一个字符串
  2. "0" * 3 =&gt; string - int =?
  3. 您无法连接两种不同的类型(此处为"000" - random_number_lengthint)。