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'
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.
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.
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.
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.
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.
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"
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