Strings
Strings hold text. Use an expression in braces to insert a value. Integer indices count Unicode scalars, and a range index returns a slice.
name = 'Ada'
greeting = 'Hello, {name}!'
print(greeting[0..5])
Output
Hello
Unescaped braces in text delimit an interpolation expression. Interpolation evaluates expressions left to right and produces a string. Use { to include a literal opening brace. String indexing returns a char. A range index produces a string slice. Indices, lengths and slice bounds count Unicode scalars. Use the binary module to work in bytes.
Chars and strings compare by their UTF-8 text. A char and a string containing the same scalar are equal and refer to the same dictionary key. Concatenating any two text values produces a string.
| Literal | Type | Value |
|---|---|---|
'A' |
char |
One Unicode scalar. |
'Atom' |
string |
Four Unicode scalars. |
'' |
string |
Empty. |
'''A''' |
string |
One Unicode scalar, explicitly a string. |
| Escape | Result |
|---|---|
\n |
Line feed. |
\r |
Carriage return. |
\t |
Tab. |
\0 |
U+0000, counted as a scalar inside Atom text. |
\\ |
Literal backslash. |
\' |
Literal apostrophe. |
\{ \} |
Literal braces. Only the opening brace needs escaping outside an interpolation. |
\u{hex} |
Scalar from one to six hexadecimal digits. |
A plain single-quoted literal occupies one line. Triple single quotes preserve whitespace including a leading or trailing newline. Both support escapes and interpolation. Interpolation formats each expression as Atom display text and concatenates the parts. Text is immutable. Indexing or slicing operates on scalar values rather than grapheme clusters. Emoji sequences and a base letter with a combining mark can have several indices. Use text.normalize when canonically equivalent sequences should compare equal. Use binary.utf8 when byte lengths or byte offsets matter.
use binary
use text
a = 'A'
b = 'Atom'
c = ''
assert(type(a) == char and type(b) == string and type(c) == string)
caption = 'é🐈'
assert(caption[1] == '\u{1F408}')
assert(caption[0..1] == 'é')
assert(count(caption) == 2 and binary.size(binary.utf8(caption)) == 6)
assert(type(convert(string, a)) == string and a == convert(string, a))
assert(text.normalize('e\u{301}') == caption[0])
note = '''First line
indented second line'''
print('{note} ({count(note)} scalars)')