2014-10-22 158 views
-4

我想減去字符串中的數字。如何減去字符串中的數字

例如:

number_str = input("number:") 

當運行該程序,我會輸入1000 300,通過空間分割。 然後我會將number_str分成first_str和second_str,將它們變成整數並進行減法。 我不知道如何將它分成兩個單獨的字符串。

+0

到目前爲止您有什麼想法或嘗試過? – Denise 2014-10-22 01:08:05

+0

哪部分你不知道該怎麼辦?如何分隔字符串分隔空間?如何將字符串轉換爲數字?如何減去數字? – abarnert 2014-10-22 01:08:11

+0

你可能想看看[str']的方法(https://docs.python.org/3/library/stdtypes.html#string-methods)和[內置函數](https:// docs .python.org/3/library/function.html),因爲所有這些步驟都有功能。並在本教程的[Sequences](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)部分解壓縮序列。 – abarnert 2014-10-22 01:10:42

回答

0
line = input('number:') 
words = line.split() 
firstNumber = int(words[0]) 
secondNumber = int(words[1]) 
result = firstNumber - secondNumber 
+0

如果你編寫中間兩行來產生一個不可預知的數字列表,而不是僅僅兩個,那麼最後一行對於新手來說是非常困難的。 – abarnert 2014-10-22 01:11:40

+0

謝謝。 line.split是我一直在尋找的東西。 – AK9309 2014-10-22 01:24:32