码迷,mamicode.com
首页 > 其他好文 > 详细

使用字符串

时间:2019-02-11 19:44:59      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:str   mat   设置   rom   初学   from   hat   14.   const   

所有的序列操作都是都是用于字符串。(索引、切片、乘法、长度)

但是因为字符串是不可变的,因此所有的元素赋值和切片赋值都是非法错误。

设置字符串的格式:精简版

以下是python中字符串格式的一些基本的用法,初学者的我了解这些已经够用了。

 1 format = ‘Hello, %s. %s enough for you?‘
 2 values = (‘world‘, ‘hot‘)
 3 print(format % values)
 4 
 5 from string import Template
 6 templ = Template(‘Hello, $who! $what enough for ya?‘)
 7 print(templ.substitute(who = ‘Eric‘, what = ‘money‘))
 8 
 9 print(‘{}, {} and {}‘.format(‘a‘, ‘b‘, ‘c‘))
10 
11 print(‘{1}, {0} and {2}‘.format(‘a‘, ‘b‘, ‘c‘))
12 
13 from math import pi
14 print(‘{name} is approximately {value:.2f}.‘.format(name = ‘Π‘, value = pi))
15 
16 from math import e
17 print(f‘Euler\‘s constant is roughly {e}‘)

自己猜猜它们每一块的执行结果吧。

看看自己是否猜得对:

Hello, world. hot enough for you?
Hello, Eric! money enough for ya?
a, b and c
b, a and c
Π is approximately 3.14.
Euler‘s constant is roughly 2.718281828459045

 

使用字符串

标签:str   mat   设置   rom   初学   from   hat   14.   const   

原文地址:https://www.cnblogs.com/FunkyEric/p/10362847.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!