使用for循环在python中反转整个字符串

时间:2019-11-13 07:57:48

标签: python python-3.x

npm run build-all

输出- looc si nohtyp 但是我想要这种类型的输出- nohtyp si

3 个答案:

答案 0 :(得分:2)

您可以按空格分割并反转每个单词,然后将它们连起来:

y = "python is cool"
for i in y.split():
    print(''.join(list(reversed(i))),end=' ')
#nohtyp si looc 

答案 1 :(得分:1)

您可以split words,然后颠倒每个word,然后join,像这样,

>>> y = "python is cool"
>>> ' '.join(x[::-1] for x in y.split())
'nohtyp si looc'

答案 2 :(得分:0)

如果您想成为loop模式的傻瓜:

y = "python is cool"
def reverse(y):
    new_s,temp_s = '', ''
    for i in range (0,len(y)):
        if y[i] == ' ' and temp_s:
                for j in range(1,len(temp_s)+1):
                    new_s += temp_s[-j]
                new_s += ' '
                temp_s = ''
        else:
            temp_s += y[i]
    for j in range(1,len(temp_s)+1):
        new_s += temp_s[-j]
    return new_s

print(reverse(y))

输出:

nohtyp si looc