在Python中,占位符用于在字符串中插入变量,并且可以指定变量的类型。以下是使用占位符的几种常见方法:
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message) 输出:My name is Alice and I am 25 years old.
2. 使用`%s`、`%d`和`%f`占位符分别表示字符串、整数和浮点数:
pi = 3.14159
message = "The value of pi is approximately %.2f." % pi
print(message) 输出:The value of pi is approximately 3.14.
3. 使用f-strings(Python 3.6及以上版本支持):
name = "Bob"
age = 25
message = f"Hello, {name}! You are {age} years old."
print(message) 输出:Hello, Bob! You are 25 years old.
4. 使用`format`函数进行格式化:
name = "Peter"
print("Hello %s." % name) 输出:Hello Peter.
5. 使用字典和`format`函数进行格式化:
info = {"username": "yiifaa", "age": 32}
message = "My name is {username}, age is {age}!"
print(message.format(info)) 输出:My name is yiifaa, age is 32!
6. 使用`str.format`方法进行格式化:
info = {"username": "yiifaa", "age": 32}
message = "My name is {username}, age is {age}!"
print("{}".format(message).format(info)) 输出:My name is yiifaa, age is 32!
以上是Python中占位符的基本用法。您可以根据需要选择合适的方法进行字符串格式化