2014-03-01 15 views
1

我有所有這些變數,而且對我來說似乎太混亂了。如何計算沒有太多變量的這個數字?

text1 = "ABCD" + " : " + "EFGH" 
text2 = str(3.06) + "% : " + "XYZ" 

# The text is not actually equal to "ABCD", "EFGH", and "XYZ" 

num1 = int(len(str(text1))) 
num2 = int(len(str(text2))) 
num3 = int(num1 - num2) 
num4 = int(num3/2) 
num5 = num4*" " 

有什麼辦法可以簡化這個嗎?

回答

2

您可以在每個變量的位置替換操作。它的工作原理類似於數學:

num = " " * int((len(text1) - len(text2))/2) 

注意這是沒有必要明確str變量text1text2因爲它們已經str類型。您可以通過打印

print(type(text1)) 

如果您正在使用Python 2.7看到這一點,那麼就沒有必要劃分轉換爲int。但是如果它是Python 3.x,那麼它就沒有必要了。

+2

另外 - len()已經產生了int,不需要再次投射 – lejlot

+0

如果OP使用Python 2.7或3.x,@lejlot不清楚。在最後一個'int/int'將會產生一個'float'。 – Christian

+0

你是對的,我預測2.7 – lejlot

1

您正在執行大量的冗餘convesions(字符串,字符串和整數到整數的)

text1 = "ABCD" + " : " + "EFGH" 
text2 = str(3.06) + "% : " + "XYZ" 

# The text is not actually equal to "ABCD", "EFGH", and "XYZ" 

num1 = len(text1) 
num2 = len(text2) 
num3 = num1 - num2 
num4 = num3/2 
num5 = num4*" " 

,你也可以在短短的一個

num5 = " " * ((len(text1)-len(text2))/2) 
2
" " * ((len(text1) - len(text2))/2) 
+1

請注意,這可以在Python 2中使用,但在Python 3中,除法返回'float',並且不能通過'float'乘以字符串。所以在提問者的原始代碼中有一個'int'不是多餘的:-) –

+0

@SteveJessop好點。 –

1

壓縮最後5個操作在Python 2 :" " * ((len(text1) - len(text2))/2)

在Python 3中:" " * ((len(text1) - len(text2))//2)(因爲你想要int eger分區)