Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用列表反转python中的单词_Python_List_For Loop_Reverse - Fatal编程技术网

使用列表反转python中的单词

使用列表反转python中的单词,python,list,for-loop,reverse,Python,List,For Loop,Reverse,因此,我必须创建一个函数,该函数采用如下列表: [d,o,g]-->每个字符都有一个位置 返回的是相反的单词。。。 到目前为止,我有: def invertido(x): largo= len(x) for i in range (0, largo/2): x[i] = x[largo -i] print x 我有以下错误:TypeError:“str”对象不支持项分配您可以直接使用Python中的索引语法来执行此操作。尝试: word_inverted

因此,我必须创建一个函数,该函数采用如下列表: [d,o,g]-->每个字符都有一个位置 返回的是相反的单词。。。 到目前为止,我有:

def invertido(x):
    largo= len(x)
    for i in range (0, largo/2):
        x[i] = x[largo -i]
    print x

我有以下错误:TypeError:“str”对象不支持项分配

您可以直接使用Python中的索引语法来执行此操作。尝试:

word_inverted = word[-1::-1]
此语法的意思是“从
word
(索引
-1
)中的最后一个字母开始,一次向后移动一个字母(末尾的
-1
),然后移动单词中的所有字母(中间的

通常,您可以使用语法
array[first:last:step]
索引数组(字符串只是一个字符数组),其中
first
是您想要的第一项,
last
是您不想要的第一项(即,您得到的最后一项是
last
之前的项)而
步骤
是每个连续项目要移动的距离


您还可以使用一些快捷方式,使用
array[:last:step]
从单词开头到
last
的所有字母,从
first
array[first::step]
结尾的所有字母,以及使用
array[:step]
的某个间隔的所有字母。最后,如果为
步骤输入负值
,则在数组中向后移动。

转换为列表,然后尝试相同的方法,或者只需
word[:-1]
。谢谢:)这对我帮助很大。