+ 2

Python query

https://code.sololearn.com/c4ze2xfVNuta/?ref=app Can somebody explain whats happening in third line of this code? And how to get the required answer in same line itself?

20th Feb 2019, 2:04 PM
Abhay Jindal
Abhay Jindal - avatar
2 Antworten
+ 7
As Kuba Siekierzyński sir has explained about the Slicing of a string, I will answer 2nd part of your Question If you want to print on the same line then you can change the 'end' parameter of a print fuction For example a= str(input()) print("Entered String is: ",a) print("reversed string is: ",end='') print(a[::-1]) Here at 3rd line i have added the end parameter, Your print function can 5 types of parameters 1) objects 2) sep {each objects are. seperated by sep. Default is ' '} 3) end 4) file {file=sys.stdout , this will write the output in the file provided the file must a object with a write method} 5) flush { if true the stream is forcibly flushed, default is False} Hence full syntax will be print(*object, sep=' ' , end='\n' , file=sys.stdout, flush= False) Hope that helped ;)
20th Feb 2019, 9:18 PM
Aaditya Deshpande
Aaditya Deshpande - avatar
+ 6
Slicing of the string is done by providing up to three parameters in the square brackets, separated with colons - [start:stop:step]. Start marks the beginning of the slice, stop marks the end and step defines every which element you want. So [2:9:2] means you want the element number 2, then 4, then 6 and 8. You can of course skip some of the arguments, which then will be left at its default -- start=0, stop=len(str), step=1. [2::2] means you will get each second element from [2] till the last one. Things get a little more complicated if you introduce negative numbers. While for start and stop they still mean elements ([-1] means the last element, [-2] second last, etc.) specifying the step as negative makes the whole slicing procedure reverse the order. It will then return the elements from stop to start backwards. Your third line does just that returning all elements from last to first, backwards. As for the second part of your sentence - print can accept numerous parameters: print('blablabla', a[::-1])
20th Feb 2019, 8:13 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar