字符串格式化方法

Python的字符串格式化有两种方式:%格式符方式和format方式

name = input("name:")
age = int(input("age:"))
job = input("job:")
# print(name,age,job)

info1 = '''
------------- info1 of %s -------------
Name:%s
Age:%d
Job:%s
'''%(name,name,age,job)
# 如果只有一个%,括号可以省略
print(info1)
# %s=string 字符串
# %d=digit 数字
# %f=浮点

info2 = '''
------------- info2 of {_name} -------------
Name:{_name}
Age:{_age}
Job:{_job}
'''.format(_name=name,
           _age=age,
           _job=job)
print(info2)

info3 = '''
------------- info3 of {0} -------------
Name:{0}
Age:{1}
Job:{2}
'''.format(name,age,job)
print(info3)

  

转载于:https://www.cnblogs.com/rouge2017/p/8280587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,字符串格式化是通过将变量的值插入到字符串中来创建新字符串的过程。以下是几种常见的字符串格式化方法: 1. 使用占位符 在字符串中使用占位符(例如%s和%d)来表示变量的值,然后通过字符串的format()方法将这些占位符替换为实际的值。例如: ``` name = "Alice" age = 30 print("My name is %s and I am %d years old." % (name, age)) ``` 输出结果为: My name is Alice and I am 30 years old. 2. 使用f-strings f-strings是Python 3.6及更高版本引入的一种格式化字符串方法。它们允许在字符串中嵌入表达式,并在字符串中使用大括号{}表示变量的值。例如: ``` name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") ``` 输出结果为: My name is Alice and I am 30 years old. 3. 使用format()方法 format()方法可以接受任意数量的参数,并使用花括号{}来表示变量的值。例如: ``` name = "Alice" age = 30 print("My name is {} and I am {} years old.".format(name, age)) ``` 输出结果为: My name is Alice and I am 30 years old. 4. 使用模板字符串 模板字符串是一种包含占位符的字符串,可以使用字符串模板库(Template)中的substitute()方法将占位符替换为实际的值。例如: ``` from string import Template name = "Alice" age = 30 template = Template("My name is $name and I am $age years old.") print(template.substitute(name=name, age=age)) ``` 输出结果为: My name is Alice and I am 30 years old.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值