我是一個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語言。邏輯似乎是正確的,但語法不工作。
你不要在Python中「創建一個空字符串數組」。查看[官方Python教程](https://docs.python.org/3.4/tutorial/index.html),你將爲自己節省很多輸入。 – TigerhawkT3
我不清楚該計劃的目標。你只是想把一個像'hello'這樣的字符串變成''helloolleh''嗎?或者是其他東西? – TigerhawkT3
@ TigerhawkT3是的,我打算把字符串'hello'變成'helloolleh'。 – Midhun