-
1、单引号定义法:name = '程序员' 2、双引号定义法:name = "程序员" 3、三引号定义法:name = """ """
如果想要定义字符串本身包含单引号,双引号 单引号定义法,可以内含双引号 双引号定义法,可以内含单引号 可以使用转移字符(\)来将引号解除效用,变成普通字符串
name = '"我爱python"' name = "\"我爱python"
-
# 字符串字面量和字符串变量的拼接
language = "数学"
mood = "让人开心的科目"
print("我爱"+ language+",数学是一门" + mood)
字符串的格式
name = "黑马程序员" message = "学IT就来 %s" % name %表示:我要占位 =s表示:将变量变成字符串放入占位的地方 %s:将内容转换成字符串,放入占位位置 %d:将内容转换成整数,放入占位位置 %f:将内容转换为浮点型,放入占位位置 注意:多个变量占位,变量要用括号括起来,并按照占位顺序填入 快速格式化 f"内容{变量}"
subject1 = "python"
subject2 = "c++"
subject3 = "java"
message = "我们学习的语言有:%s,%s,%s" % (subject1,subject2,subject3)
print(f"我们学习的语言有:{subject1,subject2,subject3}")
print(message)
class_num = 57
avg_salary = 12301
message1 ="Python大数据学科,贵州%s期,毕业平均工资:%s" % (class_num,avg_salary)
print(message1)
print("---------------------------")
字符串格式化-数字精度控制 %5d : 表示将整数的宽度控制在5位,如数字11,被设置为5d ,就会变成:[空格][空格][空格]11,用三个空格补全宽度 %5.2 : 表示将宽度控制为5,将小数点精度设置为2,小数点和小数部分也算入宽度计算 %.2 :表示指控制小数点部分 如果宽度比数字本身的宽度还小,宽度不会生效 字符串格式化-表达式的格式化 print("字符串在python中的类型名是: %s" % type("字符串"))
# example
"""
定义如下变量:
name :公司名
stock_price : 当前股价
stock_code : 股票代码
stock_price_daliy_growth_factor : 股票每日增长系数,浮点数类型,比如1.2
growth_days : 增长天数
计算,经过growth_days天的增长后,股票达到了多少钱
"""
name1 = "字节跳动"
stock_price = "19.99"
stock_code = "3030332"
print(f"公司:{name1},股票代码:{stock_code},当前股价:{stock_price}")
growth_days = input("请输入增长天数:")
stock_price_daliy_growth_factor = input("请输入每日增长系数:")
stock_price=float(stock_price)
growth_days=float(growth_days)
stock_price_daliy_growth_factor=float(stock_price_daliy_growth_factor)
stock_price_ago =stock_price * stock_price_daliy_growth_factor ** growth_days
print("每日增长系数:%.1f ,经过 %d 天的增长后,股票达到了:%.3f" % (stock_price_daliy_growth_factor,growth_days,stock_price_ago))
# input 无论里面输入的是什么类型,获取到的数据永远是字符串类型