Slicing in python
Python has a very interesting and easy-to-use Feature called "slicing" which can be useful for getting sub-string from strings, before working directly with strings, let’s see how it works.
In python, strings are sequences of type array (or list) of characters, with some differences, but in many ways one can work with these objects as if they were lists.
From this information, we may use slicing in our strings. Let’s take an example with a list.
lst = [1, 2 ,3, 4, 5, 6, 7, 8, 9, 10]
# Fazendo um slicing
>>> lst[5]
6
# Mais um slicing
>>> lst[4:7]
[5, 6, 7]
See that slicing returns us a part of the list (a subset), through two arguments specifying the initial and final position we want to get from it:
Syntax: list[start:end:step]
Now let’s see how it works with strings: Let’s say we have the following string, "Se a implementação é difícl de explicar, é uma ideia ruim"
(of python zen), let’s make some Slices in it
# Não nomei somente como "str", o python deixa mas vc sobrepoe o objeto embutido
>>> str1 = "Se a implementação é difícl de explicar, é uma ideia ruim"
# Recortando a palavra "implementação"
>>> str1[5:18]
'implementação'
# Recortando a palavra "Explicar"
>>> str1[31:39]
'explicar'
# Recortando a partir da posicção 1, até o final de 2 em 2 caracteres
>>> str1[1::2]
'eaipeetçoédfc eepia,éuaieari'
# Invertendo a string
>>> str1[::-1]
'miur aiedi amu é ,racilpxe ed lcífid é oãçatnemelpmi a eS'
Explaining the syntax:
s[pos1:pos2] # Itens a partir de pos1 até pos2-1
s[pos1:] # Itens a partir de pos1 até o final da string
s[:pos2] # Itens a partir do inicio da string até pos2-1
s[:] # Uma copia inteira da string
In all the above options you can also use the argument passo
:
s[pos1:pos2:passo]
Like pos2
represents the first element that will not be selected by slicing operation, the number of selected elements will be the difference between pos1
and pos2
, if the number of passo
for the default that is 1
Negative number for pos1
or pos2
:
That’s a Feature interesting that allows the count to be made from the end of the string/list/array instead of the start:
s[-1] # O último item
s[-5:] # Os últimos cinco itens
s[:-5] # Tudo, menos os últimos cinco itens
Negative number for the passo
:
With negative numbers attributed to passo
the result is reversed:
s[::-1] # Todos os itens de forma inversa
s[1::-1] # Os dois primeiros itens de forma inversa
s[:-5:-1] # Os últimos quatro ítens de forma reversa
s[-5::-1] # Todos os itens de forma reversa, exceto os cinco últimos
Eai Robson blz? face this will help me a lot because the logic involved is the same! ,and I was looking for an explanation like that! so I could clear my mind.
– Marcos Vinicios
Ah and answering his question about the find() method, he finds the first occurrence of a substring, returning the first occurrence index. Example:
texto = 'esse meu texto é muito bom esse' text.find('texto') # >>>4 pois a ocorrência texto começa na posição 4 do elemento
You can also offset it to it:texto.find('esse',5) # >>>27 pq é a primeira ocorrência apartir da posição 5.
And you can also delimit only one block passing one more parameter as the final position.texto.find('muito',5,26)
– Robson Silva
I’m glad you could help, in case you need me to explain the code further, just let me know. But I left very detailed in the comment in the code, and the level of python used is very basic. If it helped you I ask you to mark the question as solved, below the vote option next to the answer.
– Robson Silva
One thing you can improve on the code, is to be able to pass all the arguments, what is missing to implement is, when you pass a substring, you can pass the start parameter, It is with this to seek the substring from the start position and then from this bring the amount of characters passed by what, would be more complete and is very simple to do, if you want I’ll leave to you try to implement and train a little more python as well. Hugs.
– Robson Silva