Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template strings in F#?

Tags:

f#

I'm new to F#, and want to know if there is anything in F# similar to template strings in Python. So I can simply do something like:

    >>> d = dict(who='tim', what='car')
    >>> Template('$who likes $what').substitute(d)
    'tim likes car'
like image 679
Daniel Wang Avatar asked Dec 10 '13 01:12

Daniel Wang


People also ask

What is f {} in Python?

The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast. Example: The f or F in front of strings tells Python to look at the values inside {} and substitute them with the values of the variables if exist.

What are F-strings?

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values.

What are template strings?

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.

How do you use F in strings?

The f-strings have the f prefix and use {} brackets to evaluate values. Format specifiers for types, padding, or aligning are specified after the colon character; for instance: f'{price:. 3}' , where price is a variable name.


2 Answers

The idiomatic way of doing that in F# is with sprintf:

let newString = sprintf "First Name: %s Last Name: %s" "John" "Doe"

Additionally, you have access to the .net String.Format:

let newString = String.Format("First Name: {0} Last Name: {1}", "John", "Doe")

The benefit of the first one is that it is type-safe (i.e. you can't pass a string to an integer formatter like "%d"). As noted by Benjol in the comments, it's not possible to pass a format string to sprintf because it is statically typed. See here for more information on that.

like image 184
N_A Avatar answered Oct 28 '22 09:10

N_A


New in F# 5 is string interpolation:

let firstName = "John" 
let lastName = "Doe" 

let newString = $"First Name: {firstName} Last Name: {lastName}" 

Or without local bindings (note the triple quotes):

let newString = $"""First Name: {"John"} Last Name: {"Doe"}"""

Older versions of F# should use sprintf:

let newString = sprintf "First Name: %s Last Name: %s" "John" "Doe"
like image 42
sdgfsdh Avatar answered Oct 28 '22 09:10

sdgfsdh