字符串占位符 - 相关知识点的详细讲解

发布时间:2023-05-20

一、基础知识

1、字符串占位符是什么?

字符串占位符是一种在字符串中指定某些位置应该替换成相应的值的方式。其格式一般是以一个百分号(%)为起始,紧随其后的一个字符表示其具体的格式。占位符用于向字符串中插入变量或其他动态内容。

2、字符串占位符的格式

常用的字符串占位符有以下几种:
%s   字符串 (采用str()的显示)
%d   整数
%f   浮点数
%e   浮点数(科学计数法)
%x   十六进制整数
其他扩展可参考标准库文档。

3、代码示例

str1 = "Hello, %s!"
name = "John"
print(str1 % name)
输出:Hello, John!

二、字符串占位符的用法

1、向字符串中插入单个值

name = "John"
age = 25
str1 = "My name is %s, I'm %d years old."
print(str1 % (name, age))
输出:My name is John, I'm 25 years old.

2、向字符串中插入多个值

user_info = {
   'name': 'John',
   'age': 25,
   'city': 'New York'
}
str1 = "My name is %(name)s, I'm %(age)d years old and I live in %(city)s."
print(str1 % user_info)
输出:My name is John, I'm 25 years old and I live in New York.

3、使用元组或列表作为输入

user_info = ('John', 25, 'New York')
str1 = "My name is %s, I'm %d years old and I live in %s."
print(str1 % user_info)
输出:My name is John, I'm 25 years old and I live in New York.

4、使用字典作为输入

user_info = {
   'name': 'John',
   'age': 25,
   'city': 'New York'
}
str1 = "My name is %(name)s, I'm %(age)d years old and I live in %(city)s."
print(str1 % user_info)
输出:My name is John, I'm 25 years old and I live in New York.

三、应用场景

1、输出日志信息

import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
name = 'John'
logging.debug('The name is %s' % name)
输出到example.log文件:DEBUG:root:The name is John

2、动态生成SQL语句

user_info = {
   'name': 'John',
   'age': 25,
   'city': 'New York'
}
sql = "INSERT INTO users (name, age, city) VALUES ('%(name)s', %(age)d, '%(city)s');" % user_info
print(sql)
输出:INSERT INTO users (name, age, city) VALUES ('John', 25, 'New York');

3、批量输出文件内容

with open('example.txt') as f:
   content = f.read()
   for line in content.splitlines():
       print('%s:%d:%s' % (file_name, line_number, line))

四、注意事项

1、在使用%s占位符时,必须将字符串括在引号中。 2、确保传递给字符串方法的参数与占位符的数量匹配。 3、要避免将执行字符串占位符时可能出现的意外字符串截断,建议使用%r占位符代替%s占位符来输出变量。 4、要避免使用字符串连接符来构造SQL查询,因为这可能会导致SQL注入攻击。