一、基礎知識
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注入攻擊。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/151764.html