Assuming a is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
Answer from Anand S Kumar on Stack OverflowSo, i was just wrinting a small function to see if a string is a palindrome.
I came up with this and was happy:
def is_palindrome(to_test):
if len(to_test)<=1:
return True
elif to_test[0] == to_test[-1]:
return is_palindrome(to_test[1:-1])
else:
return FalseUntil I searched for a smaller and quicker solution and found:
def ispalindrome(s):
return s[::-1] == sI do not understand it, can someone explain what this s[::-1] means?
Thank you!
Edit: Spoke to soon, I got it. But I will leave the question here anyway.
Assuming a is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1], it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
It slices the string to omit the last character, in this case a newline character:
>>> 'test\n'[:-1]
'test'
Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:
>>> ''[:-1]
''
This works on any sequence, not just strings.
For lines in a text file, Iโd actually use line.rstrip('\n') to only remove a newline; sometimes the last line in the file doesnโt end in a newline character and using slicing then removes whatever other character is last on that line.
It means "all elements of the sequence but the last". In the context of f.readline()[:-1] it means "I'm pretty sure that line ends with a newline and I want to strip it".
It represents the 'slice' to take from the result. The first element is the starting position, the second is the end (non-inclusive) and the third is the step. An empty value before/after a colon indicates you are either starting from the beginning (s[:3]) or extending to the end (s[3:]). You can include actual numbers here as well, but leaving them out when possible is more idiomatic.
For instance:
In [1]: s = 'abcdefg'
Return the slice of the string that starts at the beginning and stops at index position 2:
In [2]: s[:3]
Out[2]: 'abc'
Return the slice of the string that starts at the third index position and extends to the end:
In [3]: s[3:]
Out[3]: 'defg'
Return the slice of the string that starts at the end and steps backward one element at a time:
In [4]: s[::-1]
Out[4]: 'gfedcba'
Return the slice of the string that contains every other element:
In [5]: s[::2]
Out[5]: 'aceg'
They can all be used in combination with each other as well. Here, we return the slice that returns every other element starting at index position 6 and going to index position 2 (note that s[:2:-2] would be more idiomatic, but I picked a weird number of letters :) ):
In [6]: s[6:2:-2]
Out[6]: 'ge'
The step element determines the elements to return. In your example, the -1 indicates it will step backwards through the item, one element at a time.
That's a common idiom that reverses a list.
a = ['a', 'b', 'c', 'd']
b = a[::-1]
print b
['d', 'c', 'b', 'a']
You can read about 'extended slices' here.
It is list indexing, it returns all elements [:] except the last one -1. Similar question here
For example,
>>> a = [1,2,3,4,5,6]
>>> a[:-1]
[1, 2, 3, 4, 5]
It works like this
a[start:end]
>>> a[1:2]
[2]
a[start:]
>>> a[1:]
[2, 3, 4, 5, 6]
a[:end]
Your case
>>> a = [1,2,3,4,5,6]
>>> a[:-1]
[1, 2, 3, 4, 5]
a[:]
>>> a[:]
[1, 2, 3, 4, 5, 6]
It's called slicing, and it returns everything of message but the last element.
Best way to understand this is with example:
In [1]: [1, 2, 3, 4][:-1]
Out[1]: [1, 2, 3]
In [2]: "Hello"[:-1]
Out[2]: "Hell"
You can always replace -1 with any number:
In [4]: "Hello World"[:2] # Indexes starting from 0
Out[4]: "He"
The last index is not included.
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]The slices [1:] and [:-1] mean all but the first and all but the last elements of the array:
>>> import numpy as np
>>> s = np.array((1, 2, 2, 3)) # four element array
>>> s[1:]
array([2, 2, 3]) # last three elements
>>> s[:-1]
array([1, 2, 2]) # first three elements
therefore the comparison generates an array of boolean comparisons between each element s[x] and its "neighbour" s[x+1], which will be one shorter than the original array (as the last element has no neighbour):
>>> s[1:] == s[:-1]
array([False, True, False], dtype=bool)
and using that array to index the original array gets you the elements where the comparison is True, i.e. the elements that are the same as their neighbour:
>>> s[s[1:] == s[:-1]]
array([2])
Note that this only identifies adjacent duplicate values.
Check this out:
>>> s=numpy.array([1,3,5,6,7,7,8,9])
>>> s[1:] == s[:-1]
array([False, False, False, False, True, False, False], dtype=bool)
>>> s[s[1:] == s[:-1]]
array([7])
So s[1:] gives all numbers but the first, and s[:-1] all but the last.
Now compare these two vectors, e.g. look if two adjacent elements are the same. Last, select these elements.
Basically, the purpose of this code is to break up strings that have camelCases into different strings, and I looked up some code samples online, and I found this solution. The code works, however, I don't quite understand what some of the syntax actually does, even after some research. I made a # comment on each line I didn't understand, explaining my confusion.
I simply just don't want to mindlessly copy code off the internet without understanding what it does!
Also, if possible, are there any lessons online you recommend I goto to learn about this concept to avoid further confusion? Thanks!
def camelCase(str):
words = [[str[0]]]
for c in str[1: ]: #What does str[1: ] do? I tried looking it up but Google isn't helpful
if words[-1][-1].islower() and c.isupper(): #I'm not quite sure what function [-1][-1] plays in this function
words.append(list(c))
else:
words[-1].append(c) #I once again don't understand the function of [-1] in this else statement
return [' '.join(word) for word in words]