How to cut string text in python by delimiting the initial substring to the final position?

Asked

Viewed 6,846 times

1

I would like to know and understand how to return the cut in text with offset. I’m a beginner in python and I’m currently on a project to migrate from Delphi to python and there are a few things I’m still learning. I have a function I need to pass to python, but I’m walking in circles.

I have a function that deals with strings, which gives what is between the beginning and the end of a given text, respecting the offset and even returning offset. # // Returns the cut result in offset text. I’ve seen python find() work the same way as Delphi posEx(). (I don’t know if my python function would be right) But I’d like to know how Find works().

#

2 answers

1


Opa Marcos, all good. Man from what I understand you’re needing a function to make cuts in certain texts, where you pass the text the starting position and the amount of characters apart from that position. If that’s what I wrote a python code that might be useful.

def split_text(obj, substring = None, start = 0, qtd = None):
    '''
    Função para corte de string.
    Você pode passar apenas o objeto de texto sem especificar nada.
    isso retornará seu objeto por inteiro.
    Agora quando o parâmetro qtd for passado sem
    o parametro start ser passado, retorna uma string na 
 quantidade informada.

    Mode de uso.
    passando apenas obj e qtd
    split_text('Seu texto completo aqui', qtd=20)
    sera retornado 20 caracteries apartir do começo da str

    split_text('seu texto aqui',start=16,qtd=7)
    retorma uma string de 7 caracteres começando na pos 
    16 

    slipt_text('seu texto aqui','texto',qtd=10)
    retorna um string com 10 caracaters apartir da palavra texto

    Lembramdo quando voce passar uma substring não passe o parametro start.
    '''

    qtd = len(obj) if qtd is None else qtd

    if substring:
        inicio = obj.find(substring)
        return obj[inicio:inicio+qtd]
    elif not substring:
        return obj[start:start+qtd]

See if it helps you, otherwise post what went wrong or how we can help you otherwise.

  • 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.

  • 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)

  • 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.

  • 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.

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.