2009-06-12 39 views
1

我的輸入是這樣的python字符串輸入問題與空白!

23 + 45 = A啓動

時,我把它當作的raw_input(),然後嘗試把它分解準確輸入,它給了我這樣的

錯誤

語法錯誤:無效的語法

的代碼是這個

k=raw_input() 
a,b=(str(i) for i in k.split(' + ')) 
b,c=(str(i) for i in b.split(' = ')) 

其總是數量+ = ASTAR

它只是當我給數字+數字= astar我沒有得到語法錯誤..!但是當我給我空白我得到了聯合錯誤

+0

你想做什麼?總是有'x + y = z'或者像'12 + 4 -3 + 5 = astart + bstart'有效嗎?你需要給我們更多的信息。 – 2009-06-12 22:09:34

回答

1

編輯:正如三聯指出的,發電機對象不是問題。分區解決方案仍然是良好的,甚至無效輸入

調用 (... for ...)只返回一個生成器對象,而不是一個元組

嘗試以下之一成立:

a,b=[str(i) for i in k.split(' + ')] 
a,b=list(str(i) for i in k.split(' + ')) 

他們返回一個列表,它可以解壓縮(假設一個分割)

或使用str.partition假設2.5或更高:

a, serperator, b = k.partition('+') 

這將始終返回即使字符串沒有找到

編輯3元組:如果你不想在你輸入的空間使用strip功能

a = a.strip() 
b = b.strip() 

編輯:固定str.partition方法,出於某種原因有錯誤的函數名稱

+0

仍然有語法錯誤 – Hick 2009-06-12 22:27:20

+1

-1。發電機可以很好地解壓。 對於confirmmatino,試試a,b =(i for for i in(1,2))。 – Triptych 2009-06-12 23:54:20

2

使用Python 2.5.2進行測試,只要在兩側只有相同的間距 o您的代碼運行良好o f代碼和輸入中的+和=。

您看起來在代碼的兩邊都有兩個空格,但輸入中只有一個在 一側。另外 - 你不必在發電機中使用str(i)。你可以做 它就像a,b = k。拆分( '+')

My cut and pastes: 

My test script: 

print 'Enter input #1:' 
k=raw_input() 

a,b=(str(i) for i in k.split(' + ')) 
b,c=(str(i) for i in b.split(' = ')) 

print 'Here are the resulting values:' 
print a 
print b 
print c 


print 'Enter input #2:' 
k=raw_input() 

a,b=k.split(' + ') 
b,c=b.split(' = ') 

print 'Here are the resulting values:' 
print a 
print b 
print c 


From the interpreter: 

>>> 
Enter input #1: 
23 + 45 = astart 
Here are the resulting values: 
23 
45 
astart 
Enter input #2: 
23 + 45 = astart 
Here are the resulting values: 
23 
45 
astart 
>>> 
1

我想我只是用一個簡單的正則表達式:

# Set up a few regular expressions 
parser = re.compile("(\d+)\+(\d+)=(.+)") 
spaces = re.compile("\s+") 

# Grab input 
input = raw_input() 

# Remove all whitespace 
input = spaces.sub('',input) 

# Parse away 
num1, num2, result = m.match(input) 
1

你可以只使用:

a, b, c = raw_input().replace('+',' ').replace('=', ' ').split() 

或[編輯補充] - 這是避免創建額外的中間字符串的另一個:

a, b, c = raw_input().split()[::2] 

Hrm - 只是意識到第二個需要空間,所以不太好。

0

與其試圖解決您的問題,我想我會指出您可以嘗試瞭解爲什麼會出現語法錯誤的基本步驟:打印您的中間產品。

k=raw_input() 
print k.split(' + ') 
a,b=(str(i) for i in k.split(' + ')) 
print b.split(' = ') 
b,c=(str(i) for i in b.split(' = ')) 

這將顯示被拆分,這可能揭示你所遇到的問題的一些光產生的實際列表元素。

我通常不是打印語句調試的忠實粉絲,但是Python的優點之一是它可以很容易地啓動解釋器並以交互方式混亂,一次一個語句,看看是什麼繼續。