程序可以将变量c中存储的特定字母开头的句子中的所有单词反转 我想知道单行和多行条件之间的区别
当我这样写的时候就可以了
l = "word searches are super fun"
c = 's'
for i in l.split():
if i[0] == c:
l = l.replace(i, i[::-1])
print(l)
这给了错误
l="word searches are super fun"
c='s'
l=l.replace(i, i[::-1]) for i in l.split() if i[0]==c
print(l)
输出应为 (单词sehcraes是有趣的) 但它是 (语法无效)
答案 0 :(得分:1)
您不能在所有情况下都使用for/if
。您可以在list comprehension
(或类似名称)中使用它
l = "word searches are super fun"
c = 's'
# create list with new words - using list comprehension
l = [ i[::-1] if i[0]==c else i for i in l.split() ]
# concatenate list into one string
l = ' '.join(l)
print(l)