zoukankan      html  css  js  c++  java
  • python字符串格式化的三种方式

    一、前言

      在我们进行python编码的时候经常需要用到字符串的格式化,下面是常用的几种字符串格式化方式。

    二、三种格式化方式

      1、%格式化

    name = 'xiaoming'
    age = '10'
    
    test = '%s is %s years old' % (name, age)
    print(test)

     output:

    xiaoqing is 10 years old

    说明:

      %s:字符串

      %d:十进制整数

      %f:浮点数

      另外,%也支持字典形式的传递,如下:

    test1 = 'Hello %(name)s,id=%(name)s' % {'id': 10, 'name': 'World'}
    print(test1)

    output:

    Hello World,id=World

      2、str.format()

        常规用法

    name = 'xiaoming'
    age = '10'
    
    test2 = 'hello, {}, you are {}?'.format(name, age)
    print(test2)

    output:

    hello, xiaoming, you are 10?

      通过位置访问

    name = 'xiaoming'
    age = '10'
    
    test2 = 'hello, {0}, you are {1}?'.format(name, age)
    print(test2)

    output:

    hello, xiaoming, you are 10?

      通过关键字访问

    name = 'xiaoming'
    age = '10'
    
    test3 = 'hello, {name}, you are {age}?'.format(name=name, age=age)
    print(test3)

    out:

    hello, xiaoming, you are 10?

      3、f格式化

    name = 'xiaoming'
    age = '10'
    
    test4 = f'hi, {name}, are you {age}?'
    print(test4)

    output:

    hi, xiaoming, are you 10?

     备注:第三种字符串格式化是python3.6以上才有的,据说性能是三者中最好的,建议采用这种

    如果低于Python3.6,可以通过pip install future-fstrings即可,在相应的py 文件里不需要加import这个库,但是需要头部加上# coding: future_fstrings

     

    知道、想到、做到、得到
  • 相关阅读:
    数组中,奇数放前偶数放后
    回溯法
    java+selenium的helloworld
    我为什么反对纯算法面试题
    算法面试题
    关于算法
    伴随开发人员成长的问题:工程重要,还是算法重要?细节重要,还是架构重要?
    数据结构和算法为什么这么重要?
    JSP网站开发基础总结《三》
    JSP网站开发基础总结《二》
  • 原文地址:https://www.cnblogs.com/Durant0420/p/14581168.html
Copyright © 2011-2022 走看看