Você pode usar o método replace
, mas passando '\r\n'
de uma vez (e não separadamente, como você fez):
texto = 'Let the bird of loudest lay\r\nOn the sole Arabian tree\r\nHerald sad and trumpet be,\r\nTo whose sound chaste wings obey.\r\n\r\nBut thou shrieking harbinger,\r\nFoul precurrer of the fiend,\r\nAugur of the fever\'s end,\r\nTo this troop come thou not near.\r\n\r\nFrom this session interdict\r\nEvery fowl of tyrant wing,\r\nSave the eagle, feather\'d king;\r\nKeep the obsequy so strict.\r\n\r\nLet the priest in surplice white,\r\nThat defunctive music can,\r\nBe the death-divining swan,\r\nLest the requiem lack his right.\r\n\r\nAnd thou treble-dated crow,\r\nThat thy sable gender mak\'st\r\nWith the breath thou giv\'st and tak\'st,\r\n\'Mongst our mourners shalt thou go.\r\n\r\nHere the anthem doth commence:\r\nLove and constancy is dead;\r\nPhoenix and the Turtle fled\r\nIn a mutual flame from hence.\r\n\r\nSo they lov\'d, as love in twain\r\nHad the essence but in one;\r\nTwo distincts, division none:\r\nNumber there in love was slain.\r\n\r\nHearts remote, yet not asunder;\r\nDistance and no space was seen\r\n\'Twixt this Turtle and his queen:\r\nBut in them it were a wonder.\r\n\r\nSo between them love did shine\r\nThat the Turtle saw his right\r\nFlaming in the Phoenix\' sight:\r\nEither was the other\'s mine.\r\n\r\nProperty was thus appalled\r\nThat the self was not the same;\r\nSingle nature\'s double name\r\nNeither two nor one was called.'
novo_texto = texto.replace('\r\n', '')
print(novo_texto)
No caso, ele troca todas as ocorrências de '\r\n'
por ''
(a string vazia), ou seja, o resultado é a string original com todos os \r\n
removidos.
Outra alternativa é usar expressões regulares, através do módulo re
e seu método sub
:
import re
texto = 'Let the bird of loudest lay\r\nOn the sole Arabian tree\r\nHerald sad and trumpet be,\r\nTo whose sound chaste wings obey.\r\n\r\nBut thou shrieking harbinger,\r\nFoul precurrer of the fiend,\r\nAugur of the fever\'s end,\r\nTo this troop come thou not near.\r\n\r\nFrom this session interdict\r\nEvery fowl of tyrant wing,\r\nSave the eagle, feather\'d king;\r\nKeep the obsequy so strict.\r\n\r\nLet the priest in surplice white,\r\nThat defunctive music can,\r\nBe the death-divining swan,\r\nLest the requiem lack his right.\r\n\r\nAnd thou treble-dated crow,\r\nThat thy sable gender mak\'st\r\nWith the breath thou giv\'st and tak\'st,\r\n\'Mongst our mourners shalt thou go.\r\n\r\nHere the anthem doth commence:\r\nLove and constancy is dead;\r\nPhoenix and the Turtle fled\r\nIn a mutual flame from hence.\r\n\r\nSo they lov\'d, as love in twain\r\nHad the essence but in one;\r\nTwo distincts, division none:\r\nNumber there in love was slain.\r\n\r\nHearts remote, yet not asunder;\r\nDistance and no space was seen\r\n\'Twixt this Turtle and his queen:\r\nBut in them it were a wonder.\r\n\r\nSo between them love did shine\r\nThat the Turtle saw his right\r\nFlaming in the Phoenix\' sight:\r\nEither was the other\'s mine.\r\n\r\nProperty was thus appalled\r\nThat the self was not the same;\r\nSingle nature\'s double name\r\nNeither two nor one was called.'
r = re.compile(r'\r\n')
novo_texto = r.sub('', texto)
print(novo_texto)
O resultado é o mesmo: todas as ocorrências de \r\n
são removidas da string.
No seu código você está trocando os caracteres por um espaço (" "
). Se é isso que deseja, pode usar texto.replace('\r\n', ' ')
ou r.sub(' ', texto)
(repare que agora existe um espaço entre as aspas). Lembrando que neste caso, a sequência \r\n
(ou seja, esses dois caracteres, sempre que aparecerem exatamente nesta ordem) será substituída por um único espaço.
Apenas para explicar porque seu código não funcionou:
remove = "\r\n"
for i in range(0, len(remove)):
new_poetry = poetry[0].replace(remove[i], " ")
Este for
chama o método replace
uma vez para \r
e outra vez para \n
.
Mas o problema é que replace
retorna outra string, deixando a original (poetry[0]
) inalterada.
Então na primeira iteração você troca todos os \r
por espaço e coloca em new_poetry
, e na segunda iteração você troca os \n
por espaço, mas o replace
é feito na string original (poetry[0]
), que ainda contém os \r
(então new_poetry
agora terá os \n
substituídos, mas os \r
não - o valor anterior, obtido na primeira iteração, que tinha somente os \r
substituídos, é sobrescrito na segunda iteração).
Já se você usar \r\n
, conforme as soluções acima, a substituição ocorrerá somente se tiver \r
seguido de \n
(e ambos serão substituídos de uma vez, por um único espaço, caso você use ' '
nos métodos de substituição - ou removidos, se você usar ''
).
As soluções acima só fazem a substituição de um \r\n
(ou seja, somente estes dois caracteres, nesta ordem). Mas se você quiser substituir também um \r
ou \n
isoladamente, pode mudar para:
import re
texto = 'Let the bird of loudest lay\r\nOn the sole Arabian tree\rHerald sad and trumpet be,\nTo whose sound chaste wings obey.'
r = re.compile(r'\r\n?|\n')
novo_texto = r.sub(' ', texto)
print(novo_texto)
Agora a regex tem alternância (o caractere |
, que significa ou), com duas opções:
\r\n?
: um \r
seguido de um \n
opcional (o ?
torna o \n
opcional), ou
\n
: o próprio caractere \n
Assim, a regex procura por \r\n
, ou somente \r
(pois o \n
depois dele é opcional), ou (|
) por apenas um \n
. Qualquer uma destas opções é substituída pela string que você passar no sub
- no exemplo acima, usei um espaço (' '
).