conversion of newlines in a string - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: conversion of newlines in a string (/thread-41431.html) |
conversion of newlines in a string - Skaperen - Jan-14-2024 what is the best function to convert newlines in a string to Unix style whether in Windows style or Mac style (or a mix of both), all in one function call? i could do this in C in a way that would not be good in Python (picking at characters one by one). RE: conversion of newlines in a string - Gribouillis - Jan-14-2024 I don't know if it is the best solution but you could try import re new_string = re.sub(rb'\r\n?', b'\n', old_string)A potential problem is the case of a Windows file which contains \r characters not followed by \n. These \r characters will be interpreted as new lines because we don't know a priori if it is a Windows file or a Mac file. RE: conversion of newlines in a string - buran - Jan-14-2024 >>> foo = 'spam\reggs\nspam\r\neggs' >>> '\n'.join(foo.splitlines()) 'spam\neggs\nspam\neggs'docs for str.splitlines() RE: conversion of newlines in a string - Skaperen - Jan-16-2024 (Jan-14-2024, 08:39 AM)Gribouillis Wrote: because we don't know a priori if it is a Windows file or a Mac file.so, \r has a different meaning depending on which. i recall that, now. i was thinking in a narrow box trying to cover potential cases. i will know a priori whether it is Windows or Mac so i could use a different function for each. i was wondering if i should implement my own set of functions or use what Python might have. |