how to give two splits on a txt

Asked

Viewed 99 times

1

I want to give two splits one to delete lines from txt and another to delete his tab in txt has name:last name ex Rafael:File the tab and ":" how can I do this?

  • 1

    Like you’re doing so far?

1 answer

1


I don’t know how you’re opening the file, but here’s what I think is the best way:

with open('FICHEIRO.txt') as f:
    for line in f:
        nome, apelido = line.split(':') # nome = Rafael, apelido.split() = Lima

If you want to keep all your ex names on a list:

Rafael:Lima
Carla:Borges

can:

nomes = []
with open('FICHEIRO.txt') as f:
    for line in f:
        nome, apelido = line.split(':') # separar linha pelos dois pontos
        nomes.append((nome, apelido.strip())) # remover a quebra de linha no apelido

print(nomes) # [('Rafael', 'Lima'), ('Carla', 'Borges')]
  • Great friend! , that’s what I wanted to do thank you so much!

  • You’re welcome @Adrianoguedes

  • However I would also like to remove the n from the lines in the result, as I would?

  • Already on top @Adrianoguedes, with .split()

  • OK thank you very much friend!

  • @Miguel to remove the \n, the correct is the .strip() and not .split(). In your code is ok, I think it was only in the comment you typed .split() instead of .strip().

  • @Adrianoguedes if the colleague’s answer answered your question, you can accept it as an answer.

Show 2 more comments

Browser other questions tagged

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