Python学习手册(第七章)字符串

Python字符串:一个有序的字符的集合,用来存储和表现基于文本的信息。Python的字符串被划分为不可变序列这一类别,意味着这些字符串所包含的字符存在从左至右的位置顺序,并且它们不可以在原处修改。字符串是序列的一个代表(还有列表和元组)。

>>> # raw字符串抑制转义
... myfile = open('C:\...\Python学习手册\text.dat','w')
  File "<stdin>", line 2
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> myfile = open(r'C:\...\Python学习手册\text.dat','w')
>>> myfile.close()
>>> myfile = open('C:\\....\\Python学习手册\\text.dat','w')
>>> myfile.write('hello')
5
>>> myfile.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>> myfile.close()
>>> path = r'C:\...\Python学习手册\text.dat','w'
>>> path
('C:\\...\\Python学习手册\\text.dat', 'w')

# 三重引号编写多行字符串块
>>> mantra = """
... Always look
... on the bright
... side of life."""
>>> mantra
'\nAlways look\non the bright\nside of life.'
>>> print(mantra)

Always look
on the bright
side of life.
# 三重引号也常用作多行注释的
# 字符串代码转换
>>> ord('s')
115
>>> chr(115)
's'
>>> S = '5'
>>> S = chr(ord(S)+1)
>>> S
'6'
>>> int('5')
5
>>> ord('5')-ord('0')
5

>>> B = '1101'
>>> I = 0
>>> while B!='':
...     I = I*2 + (ord(B[0])-ord('0'))
...     B = B[1:]
...
>>> I
13
>>> int('1101',2)
13
>>> bin(13)
'0b1101'

# 修改字符串
>>> S = 'spam'
>>> S[0] ="x"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
>>> S = S + 'SPAM'
>>> S
'spamSPAM'
>>> S = S.replace('pam','***')
>>> S
's***SPAM'

>>> 'That is %d %s bird!'%(1,'dead')
'That is 1 dead bird!'
>>> 'That is {0} {1} bird!'.format(1,'dead')
'That is 1 dead bird!'

更高级的字符串格式化表达式

基于字典的字符串格式化:

>>> "%(n)d  %(x)s"%{'n':1,'x':'spam'}
'1  spam'
>>>
>>> reply = """
... Greetings...
... Hello %(name)s!
... Your age squared is %(age)s
... """
>>> value = {'name':'Bob','age':43}
>>> print(reply % value)

Greetings...
Hello Bob!
Your age squared is 43


>>> food = 'spam'
>>> age = 35
>>> "%(age)d %(food)s"% vars()
'35 spam'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值