String
有四种表达字符串的方式:基本,多行基本,文字和多行文字。 所有字符串只能包含有效的UTF-8字符。
基本字符串用引号 "
括起来。除必须转义的字符外,任何Unicode字符都可以使用:引号、反斜杠和tab以外的控制字符(U+0000到U+0008, U+000A到U+001F, U+007F)。
str = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF."
为了方便起见,一些流行的字符有一个紧凑的转义序列。
\b - backspace (U+0008)
\t - tab (U+0009)
\n - linefeed (U+000A)
\f - form feed (U+000C)
\r - carriage return (U+000D)
\" - quote (U+0022)
\\ - backslash (U+005C)
\uXXXX - unicode (U+XXXX)
\UXXXXXXXX - unicode (U+XXXXXXXX)
多行基本字符串两边用三个引号括起来,允许换行。紧接在开始分隔符之后的换行符将被修剪。所有其他空格和换行符保持不变。
str1 = """
Roses are red
Violets are blue"""
如果要写长字符串而不引入多余的空格,可以使用“行尾反斜杠”。当一行中的最后一个非空格字符是一个未转义的\时,它将与所有的空格(包括换行符)一起被修剪,直到下一个非空格字符或结束分隔符。适用于基本字符串的所有转义序列也适用于多行基本字符串。
# The following strings are byte-for-byte equivalent:
str1 = "The quick brown fox jumps over the lazy dog."
str2 = """
The quick brown \
fox jumps over \
the lazy dog."""
str3 = """\
The quick brown \
fox jumps over \
the lazy dog.\
"""
可以在多行基本字符串的任何位置写入一个引号或两个相邻的引号。它们也可以只写在分隔符内。
str4 = """Here are two quotation marks: "". Simple enough."""
# str5 = """Here are three quotation marks: """.""" # INVALID
str5 = """Here are three quotation marks: ""\"."""
str6 = """Here are fifteen quotation marks: ""\"""\"""\"""\"""\"."""
# "This," she said, "is just a pointless statement."
str7 = """"This," she said, "is just a pointless statement.""""
文字字符串用单引号括起来。像基本字符串一样,它们必须出现在一行中
# What you see is what you get.
winpath = 'C:\Users\nodejs\templates'
winpath2 = '\\ServerX\admin$\system32\'
quoted = 'Tom "Dubs" Preston-Werner'
regex = '<\i\c*\s*>'
由于没有转义,所以无法在由单引号括起来的字符串中写入单引号。幸运的是,TOML支持文本字符串的多行版本,可以解决这个问题。
多行字面值字符串两边用三个单引号括起来,允许换行。像字面字符串一样,没有任何转义。紧接在开始分隔符之后的换行符将被修剪。分隔符之间的所有其他内容都按原样解释,不需要修改。
regex2 = '''I [dw]on't need \d{2} apples'''
lines = '''
The first newline is
trimmed in raw strings.
All other whitespace
is preserved.
'''
你可以在多行文字字符串的任何地方写上1或2个单引号,但是不允许连续使用3个或更多的单引号。
quot15 = '''Here are fifteen quotation marks: """""""""""""""'''
# apos15 = '''Here are fifteen apostrophes: '''''''''''''''''' # INVALID
apos15 = "Here are fifteen apostrophes: '''''''''''''''"
# 'That,' she said, 'is still pointless.'
str = ''''That,' she said, 'is still pointless.''''
在字面值字符串中不允许使用制表符以外的控制字符。因此,对于二进制数据,建议使用Base64或其他合适的ASCII或UTF-8编码。编码的处理将是特定于应用程序的。