简体   繁体   中英

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

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.

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.

garry doe john i hope its working for you Thanks.

If you just want to 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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