好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python之str操作详解

1. str.format():使用“{}”占位符格式化字符串(占位符中的索引号形式和键值对形式可以混合使用)。

 1 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web', 'tornado')  # 有多少个{}占位符就有多少个值与其对应,按照顺序“填”进字符串中 2 >>> string 3 'python2.7, djangoweb, tornadotornado' 4 >>> string = 'python{}, django{}, tornado{}'.format(2.7, 'web') 5 Traceback (most recent call last): 6   File "<pyshell#6>", line 1, in <module> 7     string = 'python{}, django{}, tornado{}'.format(2.7, 'web') 8 IndexError: tuple index out of range 9 >>> string = 'python{0}, django{2}, tornado{1}'.format(2.7, 'web', 'tornado')  # 也可以指定“填”进去的值(从0开始,后面的值不一定都要用上,但是要保证指定的位置是有值的)10 >>> string11 'python2.7, djangotornado, tornadoweb'12 >>> string = 'python{py}, django{dja}, tornado{tor}'.format(tor='tornado', dja='web', py=2.7)  # 可以使用键值对的形式赋值13 >>> string14 'python2.7, djangoweb, tornadotornado'15 >>> 

查看更多关于Python之str操作详解的详细内容...

  阅读:40次