谭子python学习笔记--字符串

字符串

1、字符串常见操作方法整理

操作解释备注
s = ”空字符串
s = “spanm’s’”双引号和单引号相同
s = ‘s\np\ta\x00m’转义序列
s = “”“…”“”三重引号字符串
s = r’\temp\spam’Raw字符串
s = b’spam’一种新的常量形式b’x x x’(以及对等的B’x x x’)用来创建Python 3.0中的b y t e s对象
s = u’spam’在2.6中使用的unicode字符串
s1 + s2
s * 3
合并
重复
s[i]
s[i:j]
len(s)
索引
分片
求长度
“a %s parrot” %kind字符串格式化表达式
“a {0} parrot”.format(kind)字符串格式化方法
s.find(‘pa’)字符串方法:搜索返回第一个匹配字符的位置
s.rstrip()移除右侧空格和换行符
s.repalce(‘pa’,’xx’)替换
s.split(‘,’)用展位符分隔
s.isdigit()内容测试
s.lower()短信息转换大小写转换
s.endwith(‘spam’)结束测试s = ‘hello’
s = s + ‘spam’
print s.endswith(‘spam’)
输出为True
‘spam’.join(strlist)插入分隔符
s.encode(‘latin-1’)Unicode编码等
for x in s:print(x)迭代,成员关系找出字符在h之前的字符,组成新的字符
s = ‘hellospam’
f = []
for i in s:
if i < ‘h’:
f.append(i)
print ”.join(f)
输出为:ea
‘spam’ in s
’spam’ not in s
判断子字符串是否存在
[c*2 for c in s]字符串解析s = ‘hellospam’
print [c*2 for c in s]
结果
[‘hh’, ‘ee’, ‘ll’, ‘ll’, ‘oo’, ‘ss’, ‘pp’, ‘aa’, ‘mm’]
s[:]有效的实现顶层的完整拷贝对于原地修改的对象如列表很实用
map(ord,s)以函数ord操作序列s中的每一个成员map(lambda x:x+’w’,’hhh’)

2、字符串其它的一些tips

1)格式化输出

>>> x=1234
>>> res = "integers:...%d...%-6d...%06d" %(x,x,x)
>>> res
'integers:...1234...1234  ...001234'
>>> x = 1.23456789
>>> '%-6.2f | %05.2f | %+06.1f' %(x,x,x)
'1.23   | 01.23 | +001.2'

基于字典的字符串格式化

>>> reply="""
Greetings...
Hello %(name)s!
You age squard is %(age)s
"""
>>> values = {'name':'Bob','age':40}
>>> print reply %values

Greetings...
Hello Bob!
You age squard is 40
>>> food = 'spam'
>>> age = 100
>>> vars()
{'name': 'spam', '__builtins__': <module '__builtin__' (built-in)>, 'res': 'integers:...1234...1234  ...001234', 'age': 100, '__package__': None, 'food': 'spam', 'values': {'age': 40, 'name': 'Bob'}, 'x': 1.23456789, 'reply': '\nGreetings...\nHello %(name)s!\nYou age squard is %(age)s\n', '__name__': '__main__', '__doc__': None}
>>> '%(age)d,%(food)s' %vars()
'100,spam'
>>> template = '{motto},{0} and {food}'
>>> template.format('ham',motto='spam',food=[1,2])
'spam,ham and [1, 2]'

2)字符串分割、替换、组装

>>> x = '{motto},{0} and {food}'.format(42,motto=3.14,food=[1,2])
>>> x
'3.14,42 and [1, 2]'
>>> x.split('and')
['3.14,42 ', ' [1, 2]']
>>> y = x.replace('and','but under no circumstances')
>>> y
'3.14,42 but under no circumstances [1, 2]'
>>> 
>>> s = 'abcdefgh'
>>> l = list(s)
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> '&'.join(l)
'a&b&c&d&e&f&g&h'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值