2016-11-25 60 views
0

試圖解決,我可以在一個字符串反轉每個字的問題,因爲沒有「\ 0」與C蟒蛇,我的邏輯沒有回暖的最後一個字符字符串。 任何想法,這可怎麼固定,沒有太多改動代碼字符串的最後一個字符不被拾起

Input = This is an example 
Output = sihT si na elpmaxe 

import os 
import string 

a = "This is an example" 
temp=[] 
store=[] 
print(a) 
x=0 
while (x <= len(a)-1): 

    if ((a[x] != " ") and (x != len(a)-1)): 
     temp.append(a[x]) 
     x += 1 

    else: 
      temp.reverse() 
      store.extend(temp) 
      store.append(' ') 
      del temp[:] 
      x += 1 

str1 = ''.join(store) 
print (str1) 

我的輸出被截斷的最後一個字符

sihT si na lpmaxe 
+3

您有明確排除的最後一個字符的條件。 – pvg

+4

你一直在寫c太久了。 '打印'。加入(字[:: - 1]在a.split字())' – Holloway

+0

@pvg如果我這樣做:如果((一[X] =「「)和(x = LEN! (a)))我的輸出完全截斷了最後一個單詞。輸出是:sihT si na – Fenomatik

回答

0

你必須刪除-1兩個len(a)-1and變更單(所以當x == len(a)就不會試圖讓a[x]能發出"index out of range"

while (x <= len(a)): 

    if (x != len(a)) and (a[x] != " "): 

由於pvg建議這對我的作品

import os 
import string 

a = "This is an example" 
temp = [] 
store = [] 
print(a) 

x = 0 

while (x <= len(a)): 

    if (x != len(a)) and (a[x] != " "): 
     temp.append(a[x]) 
     x += 1 
    else: 
     temp.reverse() 
     store.extend(temp) 
     store.append(' ') 
     del temp[:] 
     x += 1 

str1 = ''.join(store) 
print(str1) 
+0

仍然會出現內存違例「IndexError:字符串索引超出範圍」 – Fenomatik

+0

@Fenomatik您是否改變了順序'和'? – furas

+0

我剛剛做過,所以我假設有條件的訂單,從左到右? – Fenomatik

2

完整版,你自己不包括最後一個字符。你並不需要檢查x != len(a)-1,這樣就可以在temp字符串添加的最後一個字符。比你一旦退出循環,可以添加的最後一個字,它將被包含在temp變量。這個提示只是爲了讓你的代碼正常工作,否則你可以按照人們的建議以更短的方式在Python中完成。

0

這很簡單,無需額外的一環:

a = "This is an example" 
print(a) 
str1 = " ".join([word[::-1] for word in a.split(" ")]) 
print(str1) 

輸入和輸出:

This is an example 
sihT si na elpmaxe 
+0

得到信用@霍洛韋。他準備好評論這個答案。 – pylang

+0

人們如此之快,讓它在那裏作爲裝飾 –

+0

好吧。但自從他首先回答以來,他仍然信賴霍洛威。 – pylang

相關問題