在Python中,'' 或 "" - 这是最基本的字符串声明方式,没有特别的前缀,表示普通字符串。用于存储文本信息。
s1 = 'hello'
s2 = "world"
print(type(s1)) # 输出:<class 'str'>
print(type(s2)) # 输出:<class 'str'>
print(s1 + s2) # 输出:helloworld
注意,如果字符串内容中包含引号,可以选择使用另一种引号来包围整个字符串,以避免使用转义字符
s3 = "He said, 'Hello, world!'"
s4 = 'It\'s a beautiful day.'
print(s3) # 输出:He said, 'Hello, world!'
print(s4) # 输出:It's a beautiful day.
b'' - 表示字节字符串(Bytes literals)。这种字符串中的字符会被解释为字节值,通常用于处理二进制数据,如文件操作、网络通信等。
b_string = b'hello'
u'' - 在Python 2中表示Unicode字符串,但在Python 3中这个前缀已经被移除,因为Python 3中的所有字符串默认都是Unicode。如果在Python 3中使用它,虽然不会报错,但已经是多余的了。
# Python 2中
unicode_string = u'你好' # 使用Unicode字符
f'' - 引入了格式化字符串字面量(f-strings),这是Python 3.6及以上版本的一个特性,允许在字符串中直接嵌入表达式,并在运行时求值。
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
f-strings的增强形式,虽然不是前缀,但在Python 3.8及更高版本中,f-string中引入了=()
语法来显示表达式的名称和值,增强了可读性。
name = "Alice"
formatted_string = f"name: {name=}"
r'' - 表示原始字符串字面量(Raw string literals),在原始字符串中,所有的转义序列都会被忽略,即反斜杠\
被视为普通字符,不具有特殊含义。
这对于正则表达式、文件路径等需要原样输出反斜杠的场景非常有用。
path = r'C:\Users\Documents\file.txt'
regex = r'\d+' # 匹配一个或多个数字
b'' 和 br'' 或 rb'':前面提到了b
用于创建字节字符串,实际上,你还可以组合使用r
来创建原始字节字符串,即br''
或rb''
。这在你需要在字节字符串中使用反斜杠时不希望它作为转义字符时非常有用。
raw_byte_string = br'\nThis is a raw byte string with \n not being a newline.'