zoukankan      html  css  js  c++  java
  • python字符中加入变量

    有时候,我们需要在字符串中加入相应的变量,以下提供了几种字符串加入变量的方法:

    1、+ 连字符

    [python] view plain copy
     
    1. name = 'zhangsan'  
    2. print('my name is '+name)  
    3.   
    4. #结果为 my name is zhangsan  

    2、% 字符

    [python] view plain copy
     
    1. name = 'zhangsan'  
    2. age = 25  
    3. price = 4500.225  
    4. print('my name is %s'%(name))  
    5. print('i am %d'%(age)+' years old')  
    6. print('my price is %f'%(price))  
    7. #保留指定位数小数(四舍五入)  
    8. print('my price is %.2f'%(price))  
    9.   
    10. 结果为  
    11. my name is zhangsan  
    12. i am 25 years old  
    13. my price is 4500.225000  
    14. my price is 4500.23  

    3、format()函数

    对于变量较多的情况,加入加'+'或者'%'相对比较麻烦,这种情况下可以使用format函数
    [python] view plain copy
     
    1. name = 'zhangsan'  
    2. age = 25  
    3. price = 4500.225  
    4. info = 'my name is {my_name},i am {my_age} years old,my price is {my_price}'  
    5.     .format(my_name=name,my_age=age,my_price=price)  
    6. print(info)  
    7.   
    8. 结果为:  
    9. my name is zhangsan,i am 25 years old,my price is 4500.225  
  • 相关阅读:
    单词小课堂
    js数组
    js规范
    css
    seajs
    IDEA快捷键
    移动端设备禁止页面滑动
    sass中的!default的作用
    【数据分析 R语言实战】学习笔记 第八章 方差分析与R实现
    excel合并单元格
  • 原文地址:https://www.cnblogs.com/liqing1009/p/8967263.html
Copyright © 2011-2022 走看看