- 1.
#实现包含一个元素的元组
x=(42,);
print x;
运行结果:
>>> runfile('C:/Users/50258/.spyder2/.temp.py', wdir=r'C:/Users/50258/.spyder2')
(42,)
- 2.
x=tuple([1,2,3]);
print x;
print '-'*15;
x=tuple('Hello');
print x;
tuple函数的功能类似与list。
运行结果:
(1, 2, 3)
---------------
('H', 'e', 'l', 'l', 'o')
- 3.
#字符串格式化
#此处values只能用元组和字典(还未介绍)
forma='What is %s brother %s ?';
values=('your','name');
print forma % values;
字符串都是不可变的,无法进行分片赋值
运行结果:
What is your brother name ?
- 4.
#格式化实数
forma='Pi is : %.3f';
from math import pi;
print forma % pi;
.3表示精度保留三位小数。
运行结果:
Pi is : 3.142
- 5.
>>> from string import Template;
>>> s=Template('$x, glorious $x!');
>>> s.substitute(x='slurm');
'slurm, glorious slurm!'
使用substitute这个模板方法会用传递进来的关键字参数x, 替换字符串中的$x。
>>> s=Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
替换字段是单词中的一部分,要用大括号括起来。
>>> s=Template('MAake $$ $s!')
>>> s.substitute(s='fun');
'MAake $ fun!'
美元符号用两个$。
>>> s=Template('A $thing must never $action.')
>>> d={}
>>> d['thing']='gentleman'
>>> d['action']='show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
利用字典(还未介绍)。