Difference between revisions of "Formatted Text Literals"

('j' and 'J' options for showZeroImPart)
 
(9 intermediate revisions by 3 users not shown)
Line 1: Line 1:
 +
{{ReleaseBar}}
 +
 
''New to [[Analytica 6.0]]''
 
''New to [[Analytica 6.0]]''
  
A [[Formatted Text Literals|formatted text literal]] (or F-string for short) is a double-quoted text literal that is prefixed with an F or f.  These can include replacement expressions that are delineated by curly braces, which get replaced by the result of evaluating the expressions.
+
A [[Formatted Text Literals|formatted text literal]] (''F-string'' for short) is a concise way to define text containing expressions, such as the values of variables.
 +
 
 +
==Introduction==
  
The following is an example of an F-String that inserts the current values of x, y and x+y:
+
A [[Formatted Text Literals|formatted text literal]] (''F-string'' for short) starts with F or f preceding a text literal enclosed in double-quotes. It can include replacement expressions delineated by curly braces, which get replaced by the result of evaluating the expressions -- for example, if x=1 and y=2:
:<code>F"The value of x is {x}, y is {y} and their sum is {x+y}"</code>
+
:<code>F"The value of x is {x}, y is {y} and their sum is {x+y}" &rarr; 'The value of x is 1, y is 2 and their sum is 3'</code>
  
Although you could accomplish the same result using [[Text_Concatenation_Operator%3A_%26|text-concatenation]] as
+
You could get the same result using [[Text_Concatenation_Operator%3A_%26|text-concatenation]] as
 
:<code>"The value of x is " & x & ", y is " & y & " and their sum is " & (x+y)</code>
 
:<code>"The value of x is " & x & ", y is " & y & " and their sum is " & (x+y)</code>
the version using F-strings is more concise and easier to read.
+
but the F-string version is more concise and easier to read.
  
[[Formatted Text Literals]] aren't really literals like normal single- or double-quoted text values are.  They are instead themselves expressions whose value is determined at evaluation time. Nevertheless, because they have the syntactic appearance of literals, the term is used. The names [[Formatted Text Literals]] and [[F-Strings]] are borrowed from [https://docs.python.org/3/reference/lexical_analysis.html?highlight=formatting#formatted-string-literals Python].
+
The names [[Formatted Text Literals]] and [[F-Strings]] are borrowed from [https://docs.python.org/3/reference/lexical_analysis.html?highlight=formatting#formatted-string-literals Python]. [[Formatted Text Literals]] aren't really literals like normal single- or double-quoted text values.  Strictly, they are expressions whose value is determined at evaluation time. But, we use that term because they have the syntactic appearance of literals.  
  
 
== Syntax ==
 
== Syntax ==
  
A [[Formatted Text Literals|formatted text literal]]  starts with either <code>F"</code> or <code>f"</code>, and ends with <code>"</code>. In other words, it is a double-quoted text value prefixed with an upper or lower case F.  There can be no space between the F and the opening quote.  Within the text, expressions are inserted using curly braces, <code>{expr}</code>. When the F-String is evaluated, the expressions in curly braces are evaluated and their result is substituted for the curly braces and expression.
+
A [[Formatted Text Literals|formatted text literal]]  starts with either <code>F"</code> or <code>f"</code>, and ends with <code>"</code>. In other words, it is a double-quoted text value prefixed with an upper or lower case F.  There can be no space between the F and the opening quote.  You can insert expressions within the text using curly braces, <code>{expr}</code>. When it evaluates an F-String, it also evaluates any expressions in curly braces and substitutes in their results.
  
 
There is currently no single-quoted version of F-strings in Analytica, so you cannot write <code>f'Something'</code>.  It must use double quotes is in <code>f"Something"</code>.
 
There is currently no single-quoted version of F-strings in Analytica, so you cannot write <code>f'Something'</code>.  It must use double quotes is in <code>f"Something"</code>.
  
If you want to embed a double quote (<code>"</code>), or curly brace (<code>{</code> or <code>}</code>) in the text part of an F-string, you must double the character.  For example,  
+
To embed a double quote (<code>"</code>), or curly brace (<code>{</code> or <code>}</code>) in the text part of an F-string, you must double the character.  For example,  
 
<pre>
 
<pre>
 
  F"An F-string has the form F""some text {{ an expression : format spec }} some more text""."
 
  F"An F-string has the form F""some text {{ an expression : format spec }} some more text""."
Line 30: Line 34:
  
 
== Array abstraction ==
 
== Array abstraction ==
When your expression evaluates to an array, a separate text value is created for each cell. When you have more than one expression, the indexes of your final result will be the union of the indexes for all the expressions.  For example:<code>
+
When a curly-bracket expression evaluates to an array, it creates a text value for each cell. When you have more than one expression, the indexes of your final result will be the union of the indexes for all the expressions.  For example:<code>
 
:[[LocalIndex]] X := 1..9;
 
:[[LocalIndex]] X := 1..9;
 
:[[LocalIndex]] Y := 1..9;
 
:[[LocalIndex]] Y := 1..9;
Line 41: Line 45:
  
 
== Format Specifiers ==
 
== Format Specifiers ==
Format specifiers are optional, but when you want to specify the format, follow your expression with a colon and then with the format specifiers.  F-String format specifiers are terse by design, so as to minimize the distraction from the content and keep your formatted text literal looking as much as possible like the final result.  But being terse, they are also cryptic.  Except for numeric parts, each element of the format is denoted by a single character.  Analytica's format specifiers have several similarities to Pythons, but are not exactly the same.  
+
Format specifiers are optional, but when you want to specify the format, follow your expression with a colon and then with the format specifiers.  F-String format specifiers are terse by design, so as to minimize the distraction from the content and keep your formatted text literal looking as much as possible like the final result.  But being terse, they are also cryptic.  Except for numeric parts, each element of the format is denoted by a single character.  Analytica's format specifiers are similar to Python's, but not quite the same.  
  
You don't need a format specifier when you've set the [[Number formats|Number Format]] of your variable or [[UDF]] to be as you'd like.  Also, you have the option of using [[NumberToText]] for a more descriptive way to specify the format.
+
You don't need a format specifier when you've set the [[Number formats|Number Format]] of your variable or [[UDF]] to be as you'd like.  Also, you have the option of using [[NumberToText]] around your expression for a more descriptive way to specify the format.
  
 
A format specifier can specify the following information:
 
A format specifier can specify the following information:
Line 65: Line 69:
 
* <code>b</code>: binary
 
* <code>b</code>: binary
  
The type can be followed by the number of digits or decimals, such as <code>G12</code> for General type with 12 digits.  For suffix, exponential, general, hex and binary types, the number is the number of digits total, for fixed point and percent types it is the number of decimal places.
+
The type can be followed by the number of digits or decimals, such as <code>G12</code> for General type with 12 digits.  For suffix, exponential, general, hex and binary types, the number is the number of digits total, for fixed point and percent types it is the number of decimal places.  See [[Number formats]].
  
 
The following characters specify additional components of the number format:
 
The following characters specify additional components of the number format:
Line 71: Line 75:
 
* <code>0</code> or <code>z</code>: Show trailing zeros. If you use 0, it needs be separated in some way from the number of digits, such as by a space of '.'.  E.g., F10 is Fixed point with 10 decimals, whereas F1.0 is fixed point with 1 decimal and trailing zeros.
 
* <code>0</code> or <code>z</code>: Show trailing zeros. If you use 0, it needs be separated in some way from the number of digits, such as by a space of '.'.  E.g., F10 is Fixed point with 10 decimals, whereas F1.0 is fixed point with 1 decimal and trailing zeros.
 
* <code>,</code>: Show thousands separators
 
* <code>,</code>: Show thousands separators
* ''space'' or <code>.</code>: Ignored characters.
+
* ''space'' or <code>.</code>: Ignored characters.{{Release|6.3||
 +
* <code>'j'</code> or <code>'J'</code> controls whether a [[Complex Numbers|complex number]] with zero imaginary part displays "+0j" or not. <code>'j'</code> displays it, <code>'J'</code> does not. (New to [[Analytica 6.3]])}}
  
 
A few options not available (if you need these, use [[NumberToText]]) are: Currency symbols, use of parentheses for negative numbers, control of the ordering of currency, sign and digits.
 
A few options not available (if you need these, use [[NumberToText]]) are: Currency symbols, use of parentheses for negative numbers, control of the ordering of currency, sign and digits.
Line 81: Line 86:
  
 
=== Width and Alignment ===
 
=== Width and Alignment ===
When you specify a (minimum) width and alignment, the expression used at least that number of characters, using spaces to pad unused space.  The alignment character comes first, followed by the width, and both are required. The possible alignment characters are:
+
When you specify a (minimum) width and alignment, the expression uses at least that number of characters, using spaces to pad unused space.  The alignment character comes first, followed by the width, and both are required. The possible alignment characters are:
 
* <code>L</code> or <code>&lt;</code>: Left align
 
* <code>L</code> or <code>&lt;</code>: Left align
 
* <code>R</code> or <code>&gt;</code>: Right align
 
* <code>R</code> or <code>&gt;</code>: Right align
Line 87: Line 92:
  
 
Examples:
 
Examples:
:<code>F"π≈{pi:R10G4} π/2≈{L10G4} |π^2≈{C10G4}|"</code> &rarr; "π≈     3.142 π/2≈1.571     |π^2≈   9.87   |"
+
:<code>F"π≈{pi:R10G4}, π/2≈{pi:L10G4}, |π^2≈{pi:C10G4}|"</code> &rarr; "π≈&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3.142, π/2≈1.571&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;, |π^2≈&nbsp;&nbsp;&nbsp;9.87&nbsp;&nbsp;&nbsp;|"
 
:<code>F"Cost=${Cost:I,R15}"</code>&rarr;[[image:FStringCurrencyLeft.png]]
 
:<code>F"Cost=${Cost:I,R15}"</code>&rarr;[[image:FStringCurrencyLeft.png]]
 
:<code>F"Cost={F"${Cost:I,}":R15}"</code> &rarr;[[image:FStringCurrencyWithNumber.png]]
 
:<code>F"Cost={F"${Cost:I,}":R15}"</code> &rarr;[[image:FStringCurrencyWithNumber.png]]
Line 94: Line 99:
  
 
=== Date template ===
 
=== Date template ===
The date template is used to render date-time values. This can be specified along with a number format, so that when an expression returns an array of values with some dates and some numbers, the number format is used for numbers and the date format far dates.
+
The date template renders date-time values. This can be specified along with a number format, so that when an expression returns an array of values with some dates and some numbers, the number format is used for numbers and the date format for dates.
  
 
The date template is preceded by the letter <code>D</code>, and then continues to the closing curly brace. The date format therefore must be last and come after any alignment and width or number format.  Any spaces that appear after the D and before curly brace become part of the final text.  The date template specified in an F-string cannot contain curly braces. Otherwise, it uses the same conventions as the date template in the number format dialog.
 
The date template is preceded by the letter <code>D</code>, and then continues to the closing curly brace. The date format therefore must be last and come after any alignment and width or number format.  Any spaces that appear after the D and before curly brace become part of the final text.  The date template specified in an F-string cannot contain curly braces. Otherwise, it uses the same conventions as the date template in the number format dialog.
  
 
Example:
 
Example:
<code>F"The current time is {Today(true):Dhh:mm:ss tt}"</code> &rarr; "The current time is 03:31:38 PM"
+
* <code>F"The current time is {Today(true):Dhh:mm:ss tt}"</code> &rarr; "The current time is 03:31:38 PM"
 +
* <code>F"In the US it is {Today():DMM/dd/yyyy}, but in Europe it is {Today():Ddd/MM/yyyy}."</code> &rarr;
 +
*:::"In the US it is 03/24/2021, but in Europe it is 24/03/2021."
  
 
== See Also ==
 
== See Also ==
Line 105: Line 112:
 
* [[Text_Concatenation_Operator%3A_%26|The text-concatenation operator, &]]
 
* [[Text_Concatenation_Operator%3A_%26|The text-concatenation operator, &]]
 
* [[NumberToText]]
 
* [[NumberToText]]
 +
* [[Number formats]]
 
* [[Text values]]
 
* [[Text values]]
 
* [[JoinText]]
 
* [[JoinText]]

Latest revision as of 20:51, 27 December 2022



Release:

4.6  •  5.0  •  5.1  •  5.2  •  5.3  •  5.4  •  6.0  •  6.1  •  6.2  •  6.3  •  6.4  •  6.5


New to Analytica 6.0

A formatted text literal (F-string for short) is a concise way to define text containing expressions, such as the values of variables.

Introduction

A formatted text literal (F-string for short) starts with F or f preceding a text literal enclosed in double-quotes. It can include replacement expressions delineated by curly braces, which get replaced by the result of evaluating the expressions -- for example, if x=1 and y=2:

F"The value of x is {x}, y is {y} and their sum is {x+y}" → 'The value of x is 1, y is 2 and their sum is 3'

You could get the same result using text-concatenation as

"The value of x is " & x & ", y is " & y & " and their sum is " & (x+y)

but the F-string version is more concise and easier to read.

The names Formatted Text Literals and F-Strings are borrowed from Python. Formatted Text Literals aren't really literals like normal single- or double-quoted text values. Strictly, they are expressions whose value is determined at evaluation time. But, we use that term because they have the syntactic appearance of literals.

Syntax

A formatted text literal starts with either F" or f", and ends with ". In other words, it is a double-quoted text value prefixed with an upper or lower case F. There can be no space between the F and the opening quote. You can insert expressions within the text using curly braces, {expr}. When it evaluates an F-String, it also evaluates any expressions in curly braces and substitutes in their results.

There is currently no single-quoted version of F-strings in Analytica, so you cannot write f'Something'. It must use double quotes is in f"Something".

To embed a double quote ("), or curly brace ({ or }) in the text part of an F-string, you must double the character. For example,

 F"An F-string has the form F""some text {{ an expression : format spec }} some more text""."

which has the content: An F-string has the form F"some text { an expression : format spec } some more text".

When the curly braces are not doubled, the content between them is parsed as an expression. Optionally, the expression can be followed by a colon (:) and a format specifier. For example:

F"1/3 = {1/3 : %6}" → "1/3 = 33.333333%"

When you omit a format specifier, the number format for the current expression context is used, i.e., for the current variable or User-Defined Function, which you set using the number format dialog.

Array abstraction

When a curly-bracket expression evaluates to an array, it creates a text value for each cell. When you have more than one expression, the indexes of your final result will be the union of the indexes for all the expressions. For example:

LocalIndex X := 1..9;
LocalIndex Y := 1..9;
F"{X} * {Y} = {X*Y}"

returns a 2-D array having 81 cells:

FstringExampleXxY.png

A format specifier is static. It isn't computed and cannot vary along any index, so the same format specifier (if any) applies to every cell of the result.

Format Specifiers

Format specifiers are optional, but when you want to specify the format, follow your expression with a colon and then with the format specifiers. F-String format specifiers are terse by design, so as to minimize the distraction from the content and keep your formatted text literal looking as much as possible like the final result. But being terse, they are also cryptic. Except for numeric parts, each element of the format is denoted by a single character. Analytica's format specifiers are similar to Python's, but not quite the same.

You don't need a format specifier when you've set the Number Format of your variable or UDF to be as you'd like. Also, you have the option of using NumberToText around your expression for a more descriptive way to specify the format.

A format specifier can specify the following information:

  • The number format for numeric values
  • Minimum width (in characters) and alignment within that space
  • The date template for date-time values

All three are optional, or you may specify more than one.

Parts that aren't explicitly specified are inherited from the current variable or UDF's number format.

Number formats

A number format type can be one of the following characters:

  • S or s: Suffix
  • E or e: Exponential
  • G or g: General
  • F or f: Fixed point
  • I or i: Integer
  • P, p or %: Percent
  • B: Boolean (Prints as True or False)
  • H, h, X or x: Hexadecimal
  • b: binary

The type can be followed by the number of digits or decimals, such as G12 for General type with 12 digits. For suffix, exponential, general, hex and binary types, the number is the number of digits total, for fixed point and percent types it is the number of decimal places. See Number formats.

The following characters specify additional components of the number format:

  • '!': Display full precision
  • 0 or z: Show trailing zeros. If you use 0, it needs be separated in some way from the number of digits, such as by a space of '.'. E.g., F10 is Fixed point with 10 decimals, whereas F1.0 is fixed point with 1 decimal and trailing zeros.
  • ,: Show thousands separators
  • space or .: Ignored characters.
  • 'j' or 'J' controls whether a complex number with zero imaginary part displays "+0j" or not. 'j' displays it, 'J' does not. (New to Analytica 6.3)

A few options not available (if you need these, use NumberToText) are: Currency symbols, use of parentheses for negative numbers, control of the ordering of currency, sign and digits.

Examples:

F"π={Pi:!}" → "π=3.141592653589793"
F"The 25th power of 3 is {3^25:I,}" → "The 25th power of 3 is 847,288,609,443"
F"${profit:F2,0}" → "$17,343,300.00"

Width and Alignment

When you specify a (minimum) width and alignment, the expression uses at least that number of characters, using spaces to pad unused space. The alignment character comes first, followed by the width, and both are required. The possible alignment characters are:

  • L or <: Left align
  • R or >: Right align
  • C or ^: Center align

Examples:

F"π≈{pi:R10G4}, π/2≈{pi:L10G4}, |π^2≈{pi:C10G4}|" → "π≈     3.142, π/2≈1.571      , |π^2≈   9.87   |"
F"Cost=${Cost:I,R15}"FStringCurrencyLeft.png
F"Cost={F"${Cost:I,}":R15}"FStringCurrencyWithNumber.png

The last example shows how you can use a nested F-string to produce a fixed-width cost column while keeping the $ attached to the number.

Date template

The date template renders date-time values. This can be specified along with a number format, so that when an expression returns an array of values with some dates and some numbers, the number format is used for numbers and the date format for dates.

The date template is preceded by the letter D, and then continues to the closing curly brace. The date format therefore must be last and come after any alignment and width or number format. Any spaces that appear after the D and before curly brace become part of the final text. The date template specified in an F-string cannot contain curly braces. Otherwise, it uses the same conventions as the date template in the number format dialog.

Example:

  • F"The current time is {Today(true):Dhh:mm:ss tt}" → "The current time is 03:31:38 PM"
  • F"In the US it is {Today():DMM/dd/yyyy}, but in Europe it is {Today():Ddd/MM/yyyy}."
    "In the US it is 03/24/2021, but in Europe it is 24/03/2021."

See Also

Comments


You are not allowed to post comments.