python中format() 函数的基础及项目中的应用

format() 是 Python 中的一个字符串方法,用于格式化字符串。您可以使用大括号 {} 在字符串中插入占位符,然后在 format() 函数中提供要插入的值。

下面是一些例子:

  • 基本用法:
print('Hello, {}!'.format('world'))
# 输出: Hello, world!
 

在这个例子中,{} 是一个占位符,format('world') 中的 'world' 将插入到这个占位符的位置。

  • 您可以在一条语句中插入多个占位符:
print('Hello, {} and {}!'.format('Alice', 'Bob'))
# 输出: Hello, Alice and Bob!
 

在这个例子中,两个占位符按照在 format() 中出现的顺序被替换。

  • 也可以在占位符中使用索引,以更灵活地指定要插入的值:
print('Hello, {1} and {0}!'.format('Alice', 'Bob'))
# 输出: Hello, Bob and Alice!
 

这个例子中,占位符 {1} 将被 'Bob' 替换,占位符 {0} 将被 'Alice' 替换。

  • 还可以在占位符中使用关键字参数:
print('Hello, {name}!'.format(name='world'))
# 输出: Hello, world!

在这个例子中,占位符 {name} 将被关键字参数 name='world' 中的 'world' 替换。

 

项目实际应用:

  • headers = {"Content-Type": "application/x-www-form-urlencoded", "Authorization": "Bearer {0}".format(token)}

解析:

"Bearer {0}".format(token) 的意思是:在字符串 "Bearer {0}" 中,将 {0} 替换为 token 的值。例如,如果 token 的值为 "abcd1234",那么结果将是 "Bearer abcd1234"

所以,"Authorization": "Bearer {0}".format(token) 这句代码的作用是创建一个字典键值对,键是 "Authorization",值是 "Bearer " 后接上 token 的值。

这通常用于设置HTTP请求的头部,发送一个带有授权信息的请求。

  • def _get_data_file(self, fileName):
     currDir = os.path.dirname(os.path.realpath(__file__))
return "{}/data/{}".format(currDir, fileName)
解析:
  1. def _get_data_file(self, fileName): 这是一个方法定义,它定义了一个名为 _get_data_file 的方法,该方法需要一个参数,即文件名(fileName)。

  2. currDir = os.path.dirname(os.path.realpath(__file__)) 这行代码首先调用 os.path.realpath(__file__) 来获取当前正在执行的脚本的绝对路径,然后调用 os.path.dirname() 来获取该脚本的目录名。结果赋值给 currDir,所以 currDir 就是当前脚本所在的目录的路径。

  3. return "{}/data/{}".format(currDir, fileName) 这行代码返回一个字符串,这个字符串是通过在 currDir 后面拼接上 /data/ 和 fileName 形成的。这基本上构成了一个新的文件路径,即当前脚本目录下的 data 子目录中的一个名为 fileName 的文件。

总的来说,这个方法的作用是构造并返回一个指向特定文件的路径。这个文件位于当前脚本所在目录的 data 子目录中,文件名由方法参数 fileName 指定。



 

posted @ 2024-05-28 10:15  安琪儿一直在  阅读(21)  评论(0编辑  收藏  举报