在Python中,字符通常使用以下几种方式表示:
1. 使用单引号(`'`)或双引号(`"`)括起来的字符序列。
2. 三引号(`'''` 或 `"""`)用于表示多行字符串。
3. 转义字符,如 `\n` 表示换行,`\t` 表示制表符,`\\` 表示反斜杠本身。
4. 在字符串前加 `r` 表示原始字符串,里面的字符无需转义。
5. 字符串格式化可以使用 `%` 操作符、`f-string` 格式或 `str.format()` 方法。
例如:
```python
使用单引号
s1 = 'Hello, Python!'
使用双引号
s2 = "Hello, Python!"
使用三引号
s3 = """
Hello,
Python!
"""
转义字符
s4 = 'Hello\nWorld'
原始字符串
s5 = r'C:\path\to\file.txt'
字符串格式化
name = 'Runoob'
print('Hello %s' % name) 使用 % 操作符
print(f'Hello {name}') 使用 f-string
print('{0} {1}'.format(name, 'World')) 使用 str.format()
Python 3 默认使用 Unicode 编码来表示字符信息,这意味着可以使用任何语言的字符来表示字符串