格式化字符串与元组

来源:互联网 发布:ubuntu 16.04重装unity 编辑:程序博客网 时间:2024/06/08 19:38

1. +

当两个变量都是字符串时,可以用+连接两者进行输出。

str1="do you like"str2="me"print(str1+str2)

2. 当需要将其他类型变量与字符串变量一同输出时,可以用函数str()将变量转化成字符串变量。

str1="my age is "str2=18print(str1+str(str2))


3. % 格式化

用%可以对非字符串变量进行格式化,其中:

  • %d用于格式化整数型变量。
  • %f用于格式化浮点型变量,如果要指定小数位,可以写上%.nf,其中n代表要保留的小数位。
  • %s用于替换一段字符。
num1=2num2=1.99str1="Leona"print("the price of egg is %d"%num1)print("the price of egg is %.2f"%num2)print("%s is very hard in studying Python."%str1)

4. 元组
当字符串输出时包含了不止一个非字符串变量时,可以使用元组来实现。例如:
product="egg"number=1.99print("the price of %s is %.2f"%(product, number))
元组可以有很多个,只要按照字符串中的顺序,在括号中依次输入相应的变量名称,用逗号隔开就可以。


原创粉丝点击