Method split and rsplit, python

2

I made this little program to try to simulate the methods 'split' and 'rsplit' of Python , but when I run it 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 I choose the 'ou' tab, it creates the list with only ['pao', 'açucar'] and does not print the last word in the list. I need help finding the error.

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))
    
asked by anonymous 15.09.2018 / 18:39

2 answers

1

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

    
15.09.2018 / 19:14
1

The problem with your code is in the condition:

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

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

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 have helped.

    
15.09.2018 / 19:38