I am reading a file which has source code. I need to append 2 spaces before each line. This is what I am doing.
data = read_file data.split(/\n/).collect {|l| ' ' + l}.join('\n')
However after joining when I do puts then it prints \n literally and it is not a line break. How do I fix that?
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
To join a list with a newline character in Python: Call the join() method on a string containing a newline char ( '\n' ). Pass the list to the join method. The result will be a string containing the list items separated by a newline.
Convert array to string with newlines using join()The join('\r\n') method is used. '\r\n' is passed in as the method's argument that acts as a separator while converting the array to string values. The array elements are divided into newline using '\r\n'.
To add a line break in array values for every occurrence of ~, first split the array. After splitting, add a line break i.e. <br> for each occurrence of ~.
You need to use a double quote ("
) instead of a single quote. So replace this:
'\n'
with this:
"\n"
Read more about it here.
You might want to use \r\n
instead if you want your line-endings to be CRLF
instead of LF
(some Windows editors such as Notepad won't see a LF
linebreak).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With