简体   繁体   English

我如何在不使用函数的情况下在python中打印名称的相反名称?

[英]How do i print the reverse of name in python without using function?

Suppose i have enter a input john doe garry and i want to print garry doe john 假设我输入了john doe garryinput ,我想打印garry doe john

I have attempted this many times: 我已经尝试过很多次了:

for x in range(0,l-1):
    first  = first+' '+li[i][0]
    i-=1
first=li[l-1]+' '+first
print(first)

but it's not getting me output as I expected 但这并没有使我获得预期的输出

You can try the following: split the input, reverse the tokens using the [::-1] slice, and join them back together. 您可以尝试以下操作:分割输入,使用[::-1]片反转标记,然后join它们重新连接在一起。

input = 'john doe garry'
rev = ' '.join(input.split()[::-1])
print(rev)
# garry doe john

Hi mannish it's look like little bit improvement in your code 大家好,您的代码看起来有点改进

na = input('enter your name ')
li=na.split()
li = na.split()
l=len(li)
i=0

for x in range(0,l):
   first=first+' '+li[i-1]
   k-=1
first=first
print(first)

if your input is john doe garry then output is. 如果您的输入是john doe garry则输出是。

garry doe john i hope its working for you Thanks. garry doe john我希望它对您有用。

If you just want to print : 如果您只想print

first = input()
for i in first.split()[::-1]:
    print(i, end=' ')
 doegarryjohn(xenial)vash@localhost:~/python/stack_overflow$ python3.7 reverse.py john garry doe doe garry john 

If you would like to store it as a variable: 如果要将其存储为变量:

first = input()
f_reverse = ''
for i in first.split()[::-1]:
        f_reverse += (i + ' ')

print(f_reverse)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM