等号执行失败" ="在python中

时间:2018-04-14 23:36:20

标签: python list

我是python中的初学者,在练习时遇到了重新分配值的代码:

##Task to take the first letter of each word and place it at the end of a word, except "special characters", like "!"

entries = "I love Python, its awesome !";

transformed = entrens.split(' ') 

print(len(transformed))

for x in transformed:
    if x.isalpha():
        print(x[0], x[-1] = '', (x[-1] + x[0]) )
    else:
        x
print(transformed)

输出:

$python main.py
  File "main.py", line 13
    print(x[0], x[-1] = '', (x[-1] + x[0]) )
                      ^
SyntaxError: invalid syntax

如何在一行中重新分配价值?感谢反馈和支持

2 个答案:

答案 0 :(得分:2)

你做不到。 Python赋值是一个语句(实际上,它是一行的顶级操作),而函数的参数必须是表达式(语句的组件)。这与您无法在if / while条件中执行作业的原因相同。

这里双重违法,因为str是不可改变的;你不能修改具体的指数。即使x[-1] = '' xstr,单独行os也是非法的。

答案 1 :(得分:0)

请尝试以下操作。

entries = "I love Python, its awesome !";

transformed = entries.split(' ') # spelling error
print(len(transformed))

for x in transformed:
    if x.isalpha():
        print(x[0], x[-1], (x[-1] + x[0]) ) # delet =''
    else:
        x
print(transformed)