[英]Last character of string not being picked up
試圖解決我可以反轉字符串中每個單詞的問題,由於python中不像C那樣沒有“ \\ 0”,因此我的邏輯無法提取字符串的最后一個字符。 不知道如何在不對代碼進行太多更改的情況下解決此問題
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
如pvg
建議,您自己排除了最后一個字符。 您無需檢查x != len(a)-1
,以便可以在temp
字符串中添加最后一個字符。 退出循環后可以添加的最后一個單詞將包含在temp
變量中。 這個提示只是為了使您的代碼正常工作,否則您可以按照人們的建議在python中以更短的方式進行操作。
您已經在len(a)-1
-1
中都刪除了-1
,並更改了and
順序(因此,當x == len(a)
它不會嘗試獲取可能導致"index out of range"
a[x]
)
while (x <= len(a)):
if (x != len(a)) and (a[x] != " "):
完整版對我有用
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)
這很簡單,不需要額外的循環:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.