未提取字符串的最后一个字符

2024-04-29 12:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

试图解决一个问题,即我可以反转字符串中的每个单词,因为python中没有“\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 

Tags: store字符串importanlenisexamplethis
3条回答

您在len(a)-1中删除了-1,在and中更改了顺序(因此,当x == len(a)时,它不会试图获得a[x],因为"index out of range"

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

正如pvg所建议的,您将自己排除最后一个字符。您不需要检查x != len(a)-1,这样就可以在temp字符串中添加最后一个字符。一旦退出循环,可以添加的最后一个单词将包含在temp变量中。这个提示只是为了让您的代码正常工作,否则您可以按照人们的建议在python中以更短的方式完成。你知道吗

相关问题 更多 >