Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newlines and formatters

I recently got bit by becoming complacent writing things like

printf "\n%f\n" 3.2

instead of

printf "%s%f%s" Environment.NewLine 3.2 Environment.NewLine

My question is: is there any way to write the safe second version as nicely as the first (i.e. a special character in the format string which inserts Environment.Newline so that an argument for each newline instance in the format string isn't required)?

like image 867
Stephen Swensen Avatar asked Feb 23 '11 04:02

Stephen Swensen


People also ask

What is the difference between carriage return and line feed?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.

What is used to create newlines?

Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.

Is line feed same as New line?

LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.

How do you use newlines in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


2 Answers

How about using kprintf for a double pass, replacing \n with NewLine:

let nprintf fmt = Printf.kprintf (fun s -> s.Replace("\n", Environment.NewLine) |> printf "%s") fmt

Then in nprintf "\n%f\n" 3.2 all \n get replaced by NewLine.

like image 67
Mauricio Scheffer Avatar answered Sep 27 '22 15:09

Mauricio Scheffer


There's not an escape sequence, but you could shorten it:

[<AutoOpen>]
module StringFormatting =
    let nl = System.Environment.NewLine

//Usage
printfn "%s%f%s" nl 3.2 nl

Here is the list of character escapes on MSDN.

As an aside, I wonder what this would do:

printfn @"
%f
" 3.2
like image 40
Daniel Avatar answered Sep 27 '22 15:09

Daniel