2015-08-15 85 views
-5

我有以下輸入:如何在python中讀取浮點數和字符串?

-122.02060305 37.28598884 1427 Alderbrook Ln San Jose 95129

的輸入格式爲經度緯度目的地

爲了,他們floatfloatString

我想設置的變量currentLong到第一個浮動,並將變量currentLat轉換爲第二個浮動,並將變量desiredDestination轉換爲剩餘的輸入,即廣告禮服,所以基本上「1427 Alderbrook ... 95129」

我已經做了大部分的java,並且大多是python新手。

我沒有在命令行上運行它。我正在燒瓶項目中使用它。

回答

1

您可以將零件分割並分配給三個單獨的變量。

stri = "-122.02060305 37.28598884 1427 Alderbrook Ln San Jose 95129" 
s = stri.split() 
currentLong, second float, desiredDestination = s[0],s[1],s[2:] 
+0

我需要的currentLong和currentLat在desiredDestination作爲String時浮動,代碼'[0],s [1],s [2:]'是什麼意思? –

+0

stri沒有定義....它是什麼? –

4

str.split()需要一個可選的第二個參數,它決定了分割的次數。對於你的情況,你可以發送2作爲第二個參數,None作爲第一個參數,這樣它就可以將任何空格的字符串分割成2次。代碼 -

s = "<your string>" 
currentLong, currentLat, desiredDestination = s.split(None,2) 

然後,如果你需要currentLong和currentLat的花車,你就需要使用float()將它們轉換成浮動,示例 -

currentLong, currentLat = float(currentLong), float(currentLat) 

示例 -

>>> s = "-122.02060305 37.28598884 1427 Alderbrook Ln San Jose 95129" 
>>> s.split(None,2) 
['-122.02060305', '37.28598884', '1427 Alderbrook Ln San Jose 95129'] 
+0

第二個參數被稱爲['maxsplit'](https://docs.python.org/2/library/stdtypes.html#str.split)。 –

+0

@AnandSKumar它給我一個錯誤,當我打電話: 'S = myInput' '經度,緯度,目的地= s.split(無,2)' 究竟有什麼maxsplit @BhargavRao –

+0

什麼錯誤? –

相關問題