【问题标题】:Last character of string not being picked up未拾取字符串的最后一个字符
【发布时间】:2016-11-25 22:19:42
【问题描述】:

试图解决我可以反转字符串中每个单词的问题,由于与 C 不同,python 中没有“\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 

【问题讨论】:

  • 您的条件明确排除了最后一个字符。
  • 你写 c 的时间太长了。 print ' '.join(word[::-1] for word in a.split())
  • @pvg 如果我这样做:如果 ((a[x] != " ") and (x != len(a))) 我的输出完全截断了最后一个单词。输出是:sihT si na
  • @pvg 和 while 循环,如果我这样做:while (x
  • 目前尚不清楚您为什么不想更改代码,但正如@Holloway 所展示的,您尝试做的事情可以在一条短线中以 Python 方式完成。有理由维护您的代码吗?

标签: python arrays string list


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您已经删除了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)
    

    【讨论】:

    • 仍然出现内存冲突“IndexError: string index out of range”
    • @Fenomatik 你在and 中更改订单了吗?
    • 我刚做了,所以我假设条件有一个顺序,从左到右?
    • 它必须首先检查x != len(a),当它为假时,它不会做a[x],它给出"index out of range"
    • 它工作得非常好,了解到有一个从左到右的条件检查。你的回答修复了这个错误,不像其他人给我一种使用方法的方法。
    【解决方案3】:

    非常简单,不需要额外的循环:

    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
    

    【讨论】:

    • 人这么快,就当摆设吧
    • 确实如此。有任何疑问吗?@pylang
    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 2011-08-17
    • 2017-05-23
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多