Split and rsplit methods, python

Asked

Viewed 711 times

2

I made this little program to try to simulate the methods 'split' and 'rsplit' of Python, but when I run it does not print the last sentence of the string. For example, if in the string I type 'pao ou açucar ou café' and choose the separator 'ou', it creates the list only with ['pao', 'açucar'] and does not print the last word on the list. I need help finding the bug.

def separa(string):
    separador = input("Digite o separador: ")
    lista = []
    x = 0
    for i in range(string.count(separador)+1):
        palavra = ''
        for j in range(x, len(string)):

            if string[j:j+len(separador)] == separador:
                lista.append(palavra)
                x = j+len(separador)
                break

            palavra += string[j]

    return lista

string = input("Digite a string: ")
print(separa(string))

2 answers

1


Basically your code just adds words found in the list before a tab. Like its last word (in this case, "coffee") does not have a separator (in this case, "or") after it, the code does not enter the condition if string[j:j+len(separador)] == separador:, which prevents this last word from being added to the list with lista.append(palavra)

  • I think I got it. I removed the variable 'word' from the program and each time the first is run I add an empty variable to the list and add the letters of the string until it arrives in the separator. http://prntscr.com/kus0wn

1

The problem in your code is in condition:

if string[j:j+len(separador)] == separador

Not that she is logically wrong but that she stipulates that only if the string current in the iteration is equal to the separator the word then stored in the variable palavra should then be added to the end of the list but the point is that in your given example 'pao ou açucar ou café' coffee comes after the separator so it will not be added to the end of the printing list as well as result ['pao', 'açucar']. One way that can be done is to add the word before returning the list this way:

def separa(string):
    separador = input("Digite o separador: ")
    lista = []
    x = 0
    for i in range(string.count(separador)+1):
        palavra = ''
        for j in range(x, len(string)):

            if string[j:j+len(separador)] == separador:
                lista.append(palavra)
                x = j+len(separador)
                break

            palavra += string[j]
    lista.append(palavra) # Adiciona a última palavra 
    return lista

string = input("Digite a string: ")
print(separa(string))

I hope I’ve helped.

Browser other questions tagged

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