因此,我正在处理的脚本的一部分是由几个单词组成的列表。我希望Python逐个遍历单词并反转每个单词。
我试着这样做:
我们假设我输入'Hello world这是一个python脚本'
def main():
print()
ptext = input('Please input the plaintext...')
ctext = ''
plist=ptext.split(' ')
for item in plist:
i = len(item)
while i>=0:
ctext = ctext + str(item)[i]
i=i-1
print()
print('The ciphertext is: ',ctext.lower()) #Print out the ciphertext
print()
但我一直在接受:
Traceback (most recent call last):
File "<pyshell#137>", line 2, in <module>
print((item)[i],end =(' '))
IndexError: string index out of range
我清楚地告诉脚本i=len(item)
,那么它怎么能超出范围?
我最好而且唯一的猜测就是它花费了像'world'这样的单词的长度为5并将其用在像'is'或'a'这样的单词上。有可能告诉Python只取每个单词的长度吗?我无法想办法。
答案 0 :(得分:4)
替换:
ctext = ctext + str(item)[i]
使用:
ctext = ctext + str(item[i])
# ^ access index of item
并将i
初始化为:
i = len(item) - 1 # because index starts with 0, and can be retrieved till `len - 1`
答案 1 :(得分:3)
字符串的第一个索引是0,最后一个是“长度 - 1”。因此,您需要设置i = len(item) - 1
,因为在第一次迭代中,您基本上会尝试访问str(item)[len(item)]
。
除此之外,str()
调用不是必需的,所以只需item[i]
。
另请注意,如果您想“反转”一个字符串,您实际上可以reversed_string = original_string[::-1]
。 [::-1]
表示它应该返回字符串,但是从结尾处开始并逐步到达一个字符。