2015-10-18 189 views
-1

我是一個python初學者。我創建了一個代碼來讓用戶輸入字符串到迴文(或者說我想)。但主要問題是我不知道如何創建一個char類型的空數組(即字符串)。當我編譯我的代碼時,我得到一個語法錯誤:File "convert to pallindrome.py", line 14, in <module> s1[j]=s2[y-i]。我不知道這是否是我創建的空數組的問題。請幫我解決這個問題。無法在Python中創建一個空數組

s2=raw_input('Enter the s2: ') #read the string from user 
x=len(s2) 
y=x-1 
s1=[20]   #another array to hold the new string 
j=0 
if len(s2)%2==0:      #if length of string is even 
    for i in range(0,y/2-1):  #do until i<=half of string length 
      if s2[i]==s2[y-i]: 
        s1[j]=s2[i] 
        j=j+1   #if characters are equal then copy the character to array 
      elif s2[i]!=s2[y-i]: 
        s1[j]=s2[i] 
        j=j+1 
        s1[j]=s2[y-i] 
        j=j+1   #if characetrs are not equal then copy both the letters 
    elif len(s2)%2!=0:      #if length of string is odd 
    for i in range(0,y/2-1): 
      if s2[i]==s2[y-i]: 
        s1[j]=s2[i] 
        j=j+1 
      elif s2[i]!=s2[y-i]: 
        s1[j]=s2[i] 
        j=j+1 
        s1[j]=s2[y-i] 
        j=j+1   #do same as above 
z=2*len(s1)    #get 2xlength of string 
if z%2==0: 
    for i in range(0,z-1): 
      if i<=z/2: 
        s1[z-i]=s1[i] #copy first half to the second half of string to create the pallindrome. 
    if z%2!=0: 
    for i in range(0,z-1): 
      if i<=(z/2)-1: 
        s1[z-i]=s1[i]    
    print s1    #print pallindrome 

我已經用C編程邏輯完成了這一步,因爲我來自C語言。邏輯似乎是正確的,但語法不工作。

+0

你不要在Python中「創建一個空字符串數組」。查看[官方Python教程](https://docs.python.org/3.4/tutorial/index.html),你將爲自己節省很多輸入。 – TigerhawkT3

+0

我不清楚該計劃的目標。你只是想把一個像'hello'這樣的字符串變成''helloolleh''嗎?或者是其他東西? – TigerhawkT3

+0

@ TigerhawkT3是的,我打算把字符串'hello'變成'helloolleh'。 – Midhun

回答

1

根據您最近在另一個答案評論,我建議建立一個list,並通過它遍歷:

>>> s = 'abcdcaa' 
>>> l = list(s) 
>>> for idx,val in enumerate(l): 
...  if val != l[-idx - 1]: 
...   l[-idx - 1] = val 
... 
>>> result = ''.join(l) 
>>> print(result) 
abcdcba 

翻譯一行一個C算法行成Python代碼是混亂的處方。用目標語言設計你的算法。

+0

爲什麼要創建一個列表?你可以迭代一個字符串,因爲它也是一個序列。 –

+0

@BurhanKhalid - 因爲我想改變它。 – TigerhawkT3

+0

@ TigerhawkT3謝謝。這是新的。感謝這樣一個精心設計的答案。 – Midhun

-1

你不應該在Python中這樣編寫代碼,但在這裏回答你的問題是你如何擁有一個可以操作的特定長度的空數組。

# Make 20 length array of chars 
import array 
s = array.array('c', " "*20) 

# Set some chars 
s[10] = "A" 

# Show it 
print "".join(s)