Python 基础,在字符串中引用变量
今天有人问这方面的问题,简单总结一下。
+ 连字符
name = 'zhangsan'
print('my name is ' + name)
#结果为:
my name is zhangsan
% 字符
name = 'zhangsan'
age = 25
price = 1500.225
print('my name is %s' %(name)) #%s代表字符串
print('i am %d' %(age) + ' years old' ) #%d代表整型
print('price is %f' %(price)) #%f代表浮点型
print('price is %.2f' %(price)) #保留指定位数小数(四舍五入)
#结果为:
my name is zhangsan
i am 25 years old
price is 1500.225000
price is 1500.23
format( ) 函数
name = 'zhangsan'
age = 25
price = 1500.225
#调用format方法,注意字符串内的变量加{}
info = 'my name is {my_name},i am {my_age} years old,price is {my_price}'.format(my_name=name,my_age=age,my_price=price)
print(info)
#结果为:
my name is zhangsan,i am 25 years old,my price is 1500.225
good
还有一种简单的 😀:
f’my name is {name}’
补充一个