+ 1

Why does this code show error

Reversing a string https://code.sololearn.com/c6TwUA1h5h1M/?ref=app

3rd Apr 2020, 12:01 PM
Alen Antony
Alen Antony - avatar
6 Respostas
+ 2
reverse is to List you need s = input() print(s[::-1])
3rd Apr 2020, 12:12 PM
Marco
Marco - avatar
+ 2
String could be treated as a list, IF YOU TURN IT TO A LIST: s = input() print(s) # output: ABC s = list(s) # s is now a list of char s.reverse() # reverse() modify the list in place, no return value (None) print(s) # output ['C','B','A'] s = ''.join(s) # turn the list of char to a string print(s) # output CBA Definitively, it's shorter (and more elegant/pythonistic) to do s[::-1] to reverse a string ^^ String could be compared to special imutable list of char (a tuple of char, in fact), so operation on its elements (modify the list in place) cannot work: that's why string could be treated as list, but wth some limitation ;) On the other hand, reversed() built-in function don't modify the list in place but return a new one: s = input() # ABC print(reverse(s)) # output <reversed object at ...> print(''.join(reversed(s)) # output 'BCA' ... well, shorter, but not as much as a s[::-1] :P
3rd Apr 2020, 2:22 PM
visph
visph - avatar
+ 2
Thanks
3rd Apr 2020, 3:28 PM
Alen Antony
Alen Antony - avatar
+ 1
String can be treated as a list right
3rd Apr 2020, 12:22 PM
Alen Antony
Alen Antony - avatar
+ 1
Not exactly. String can be treated as a list but a string object differs from a list
3rd Apr 2020, 12:48 PM
Salman Nazeer
Salman Nazeer - avatar
+ 1
Alen Antony You can use SORTED function. s=input() print(sorted(s, reverse = True)) Suppose that input is "hello" Output would be ["o","l","l","e","h"] But you want it to be joined together, so use JOIN, in the beginning of line. print("".join(sorted(s, reverse = True))) You can also use print(s[::-1]), if you know about slicing and stuff.
3rd Apr 2020, 2:09 PM
maf
maf - avatar