Stripping new lines from strings?

CHRIS unk at unk.ororr
Tue Aug 15 06:11:11 EDT 2000


ajung at suxers.de wrote:

> CHRIS <unk at unk.ororr> wrote:
> 2qy
> 2qyWhat is the best (fastest) way to strip new line characters from a
> 2qystring in Python? In C I would do:
> 2qy
> 2qychar *p;
> 2qyp = strchr(str, '\n');
> 2qyif(p)
> 2qy  *p = '\0';
> 2qy
> 2qy/* repeat process for '\r' character */
>
> Usually I use the following:
>
> lines = open('myfile','r').readlines()
> for l in lines:
>         l = l[:-1]
>    ...

>From what I understand of Python file I/O, there is no guarantee that
returned lines all contain new lines characters so, it may clip the last
line's ending character. And even then, if it is used on a Windows file,
it would skip the '\r' character.

>
>
> Cheers,
> Andreas






More information about the Python-list mailing list