当前位置: 代码网 > it编程>前端脚本>Python > Python 中字符串修饰符详解

Python 中字符串修饰符详解

2024年07月04日 Python 我要评论
1. 原始字符串 (raw string) - r 或 r使用 r 或 r 前缀,可以告诉 python 字符串中的所有反斜杠都是普通字符,而不是转义字符。这在处理文件路径、正则表达式等情况下非常有用

1. 原始字符串 (raw string) - rr

使用 rr 前缀,可以告诉 python 字符串中的所有反斜杠都是普通字符,而不是转义字符。这在处理文件路径、正则表达式等情况下非常有用。

path = r'c:\new_folder\test.txt'  # 原始字符串

2. 格式化字符串 (formatted string) - ff

使用 ff 前缀,可以在字符串中嵌入表达式。这些表达式在运行时会被计算,并将结果插入到字符串中。这种字符串被称为 f-string,是在 python 3.6 引入的。

name = "alice"
age = 30
message = f'{name} is {age} years old.'  # 格式化字符串

3. unicode 字符串 - uu

在 python 3 中,所有字符串默认都是 unicode,因此 u 前缀通常不再需要。但是,在 python 2 中,它用于创建 unicode 字符串。

# 在 python 3 中:
text = u'hello, world!'  # unicode 字符串
# 在 python 2 中:
text = u'hello, world!'  # unicode 字符串

4. 字节字符串 (byte string) - bb

使用 bb 前缀来创建字节字符串,而不是文本字符串。字节字符串用于处理二进制数据,常用于文件 i/o 和网络传输。

data = b'hello, world!'  # 字节字符串

5. 三重引号 (triple quotes)

三重引号可以用于定义跨多行的字符串。这种字符串可以用三重单引号 (''') 或三重双引号 (""") 定义。

multiline_str = """this is a
multiline string that spans
multiple lines."""

6. 组合使用修饰符

可以组合使用字符串修饰符。例如,既要使用原始字符串,又要进行格式化:

path = r'c:\new_folder\test.txt'
name = "alice"
message = fr'{name}\'s file is located at {path}'
print(message)
# output: alice's file is located at c:\new_folder\test.txt

示例代码

# 使用原始字符串
raw_path = r'c:\users\example\documents\file.txt'
print(raw_path)
# 使用格式化字符串
name = "john"
age = 28
greeting = f'hello, {name}. you are {age} years old.'
print(greeting)
# 使用 unicode 字符串
unicode_str = u'こんにちは世界'  # 这在 python 3 中默认就是 unicode
print(unicode_str)
# 使用字节字符串
byte_str = b'this is a byte string'
print(byte_str)
# 使用多行字符串
multiline_str = """this is a string
that spans multiple
lines."""
print(multiline_str)
# 组合使用原始和格式化字符串
file_path = r'c:\users\example\documents'
filename = "file.txt"
full_path = fr'{file_path}\{filename}'
print(full_path)

到此这篇关于python 中字符串修饰符的文章就介绍到这了,更多相关python 字符串修饰符内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com