python r, b, u, f 前缀详解

1、r前缀

一般来说,'\n'是一个换行符,是一个字符串;而加上r为前缀后,不会以任何特殊方式处理反斜杠。因此,r"\n" 是包含 '\' 和 'n' 的双字符字符串;示例如下:

python 复制代码
>>> print(r'\n')
\n
>>> print('\n')


>>>

"r"也常用于正则表达式中,\b在正则中代表空字符串

python 复制代码
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.findall('\bf[a-z]*', 'which foot or hand fell fastest')
[]
>>>

以"r"为前缀的字符串,表示的是原始字符串。相对于普通字符串,原始字符串中的内容会原样输出。即使字符串中含有转义字符,如常见的换行符"\n"、缩进符"\t"等,在原始字符串中它们不会进行转义,都会原样输出。

详见正则链接

2、b前缀

加上b前缀代表是byte类型,示例如下:

python 复制代码
>>> type('sss')
<class 'str'>
>>> type(b'sss')
<class 'bytes'>
>>>

其中有三种情况,如下所示:

  • Single quotes: b'still allows embedded "double" quotes' 即单引号可以包含双引号
  • Double quotes: b"still allows embedded 'single' quotes" 即双引号可以包含单引号
  • Triple quoted: b'''3 single quotes''', b"""3 double quotes""" 即三引号可以包含单引号,也可以包含双引号

详见byte链接

3、u 前缀

u''代表的是对字符串进行unicode编码。python3.0以上的版本,默认的编码就是UTF-8编码,而在2.0版本,python使用的是ascii编码

4、f 前缀

python 复制代码
>>> var1='hello world'
>>> print(f'i am lichf {var1}')
i am lichf hello world
>>>

详见我的另一篇介绍format的文章

详见f-string链接

相关推荐
极梦网络无忧2 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger2 小时前
【Python】操作Excel文件
python·excel
XLYcmy3 小时前
一个针对医疗RAG系统的数据窃取攻击工具
python·网络安全·ai·llm·agent·rag·ai安全
Islucas3 小时前
Claude code入门保姆级教程
python·bash·claude
萝卜白菜。4 小时前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
赵钰老师4 小时前
【ADCIRC】基于“python+”潮汐、风驱动循环、风暴潮等海洋水动力模拟实践技术应用
python·信息可视化·数据分析
爬山算法4 小时前
MongoDB(80)如何在MongoDB中使用多文档事务?
数据库·python·mongodb
YuanDaima20484 小时前
基于 LangChain 1.0 的检索增强生成(RAG)实战
人工智能·笔记·python·langchain·个人开发·langgraph
RopenYuan5 小时前
FastAPI -API Router的应用
前端·网络·python