Chinaunix首页 | 论坛 | 博客
  • 博客访问: 763926
  • 博文数量: 99
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1163
  • 用 户 组: 普通用户
  • 注册时间: 2016-09-22 09:50
个人简介

一个守望数据库的老菜鸟

文章分类

全部博文(99)

文章存档

2019年(21)

2018年(17)

2017年(37)

2016年(24)

我的朋友

分类: Python/Ruby

2017-08-24 11:34:09

博客文章除注明转载外,均为原创。转载请注明出处。
本文链接地址:http://blog.chinaunix.net/uid-31396856-id-5769564.html

Python数据类型--strings
strings字符串类型的特点:
字符的有序集合;没有字符(char)的概率,都是字符串;字符串是不可变的序列

1.字符串相关操作:


2.索引和分片
利用下标进行索引
s = 'hello,world'
进行索引:
 s[0], s[-2]
('h', 'l')
进行分片:
 s[1:3], s[1:], s[:-1]
('el', 'ello,world', 'hello,worl')

3.字符串常用函数
(1)和大小写相关的函数
upper 将字符串转换为大写
lower 将字符串转换为小写
isupper判断字符串是否都为大写
islower判断字符串是否都为小写
swapcase将字符串中的大写转换为小写、小写转换为大写
capitalize 将首字母转换为大写
istitle判断字符串是不是一个标题

(2)判断字符的函数
  s.isalpha如果字符串只包含字母,并且非空,则返回True,否则返回False
  s.isalnum如果字符串值包含字母和数字,并且非空,则返回True,否则返回False
  s.isspace如果字符串值包含空格、制表符、换行符,并且非空,则返回True,否则返回False
  s.isdecimal如果字符串只包含数字字符,并且非空,则返回True,否则返回False
  s.isdigit判断

(3)查找类函数
   find查找子串出现在字符串中的位置,如果查找失败,则返回-1
   index与find函数作用类似,如果查找失败,则抛出ValueError异常
   rfind与find函数作用类似,区别在于rfind是从后向前查找
   rindex与index函数作用类似,区别在于rindex是从后向前查找

(4)字符串匹配函数
后缀匹配endswith
前缀匹配startswith
例如:
[item for item in os.listdir('.') if item.endswith('.txt')]
[item for item in os.listdir('.') if item.startswith('mysql-bin.')]

4.字符串操作
(1)join函数用于字符串拼接
比如
", ".join(fruits)等价于
s = ", "
s.join(fruits)
再比如:

name = 'fruits' '*'.join(name)

(2)split函数:进行拆分
(3)replace替换,例如
print '%s replace t to *=%s' % (str,str.replace('t', '*'))
print '%s replace t to *=%s' % (str,str.replace('t', '*',1))

(4)字符串去空格及去指定字符
去两边空格:str.strip()
去左空格:str.lstrip()
去右空格:str.rstrip()
去两边字符串:str.strip('a'),相应的也有lstrip,rstrip

(5)字符串格式化-format函数 
例如:
'{} {}'.format(42,'spam')
'{1} {0}'.format(42,'spam')
'{name} {age}'.format(age=42,name='spam')
'He is {name} {age}'.format(age=42,name='spam')
---End
阅读(1677) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~