Python内置数据结构之“字符串”

这篇文字主要学习一下Python中的常用数据结构:字符串

字符串join连接

"string".join(iterable) -> str
		1.将可迭代对象连接起来,使用string作为分隔符
		2.可迭代对象本身元素都是字符串
		3.返回一个新字符串
	举个栗子:
		>>> ','.join("abc")
		'a,b,c'
		>>> lst = ['1','2','3']
		>>> '.'join(lst)
		1.2.3
		>>> lst = ['1',['2','3'],'4']
		>>> '.'join(lst)
	Traceback (most recent call last):
		File "<pyshell#7>", line 1, in <module>
		 	'.'.join(['1',['2','3'],'4'])
	 TypeError: sequence item 1: expected str instance, list found
	 这里出现报错原因,是因为可迭代对象lst = ['1',['2','3'],'4']中的元素不都是字符串

字符串分割

split(sep=None, maxsplit=-1) -> list of strings
	1.从左至右
	2.sep 指定分割字符串,缺省的情况下空白字符串作为分隔符
	3.maxsplit 指定分割的次数,-1 表示遍历整个字符串
举个栗子:
	>>> s1 = "I'm \ta super student."
	>>> s1.split()
	["I'm", 'a', 'super', 'student.']
	>>> s1.split('s')
	["I'm \ta ", 'uper ', 'tudent.']
	>>> s1.split('super')
	["I'm \ta ", ' student.']
	>>> s1.split('s',maxsplit=1)
	["I'm \ta ", 'uper student.']
	
rsplit(sep=None, maxsplit=-1) -> list of strings
	1.从右向左
	2.sep 指定分割字符串,缺省的情况下空白字符串作为分隔符
	3.maxsplit 指定分割的次数,-1 表示遍历整个字符串

splitlines([keepends]) -> list of strings
	1.按照行来切分字符串
	2.keepends 指的是是否保留行分隔符
	3.行分隔符包括\n、\r\n、\r等
举个栗子:
	>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
	['ab c', '', 'de fg', 'kl']
	>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
	['ab c\n', '\n', 'de fg\r', 'kl\r\n']

partition(sep) -> (head, sep, tail)
	1.从左至右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回头、2个空元素的三元组
	2.sep 分割字符串,必须指定
举个栗子:
	>>> s1 = "I'm a super student."
	>>> s1.partition('s')
	("I'm a ", 's', 'uper student.')
	>>> s1.partition('w')
	("I'm a super student.", '', '')
	
rpartition(sep) -> (head, sep, tail)
	1.从右至左,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回2个空元素和尾的三元组

字符串大小写

  • upper() :全大写
  • lower():全小写
  • swapcase():交互大小写

字符串排版

  • title() -> str:标题的每个单词都大写
  • capitalize() -> str:首个单词大写
  • center(width[, fillchar]) -> str:width 打印宽度,fillchar 填充的字符
  • zfill(width) -> str:width 打印宽度,居右,左边用0填充
  • ljust(width[, fillchar]) -> str 左对齐
  • rjust(width[, fillchar]) -> str 右对齐

字符串修改

replace(old, new[, count]) -> str
	1.字符串中找到匹配替换为新子串,返回新字符串
	2.count表示替换几次,不指定就是全部替换
举个栗子:
	>>> 'www.magedu.com'.replace('w','p')
	'ppp.magedu.com'
	>>> 'www.magedu.com'.replace('w','p',2)
	'ppw.magedu.com'

strip([chars]) -> str
	1.从字符串两端去除指定的字符集chars中的所有字符
	2.如果chars没有指定,去除两端的空白字符
举个栗子:
	>>> s = "I am very very very sorry"
	>>> s.strip('I')
	' am very very very sorry'
	
	>>> s.strip('Iy')
	' am very very very sorr'
	
	>>> s.strip('Iyr')
	' am very very very so'
	
我理解的规则是:首先从左边开始一个字符一个字符的找,只要寻找的字符包含在[chars]字符集中,就删除,直到找到第一个不包含在内的就停止,然后从右边开始找一遍。

lstrip([chars]) -> str:从左开始
rstrip([chars]) -> str:从右开始

字符串查找

find(sub[, start[, end]]) -> int:
	在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到返回-1

rfind(sub[, start[, end]]) -> int:
	在指定的区间[start, end),从右至左,查找子串sub。找到返回索引,没找到返回-1

index(sub[, start[, end]]) -> int:
	在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

rindex(sub[, start[, end]]) -> int:
	在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

count(sub[, start[, end]]) -> int:
	在指定的区间[start, end),从左至右,统计子串sub出现的次数

字符串判断

endswith(suffix[, start[, end]]) -> bool:
    	在指定的区间[start, end),字符串是否是suffix结尾
    
startswith(prefix[, start[, end]]) -> bool:
    	在指定的区间[start, end),字符串是否是prefix开头

字符串判断 is系列

- isalnum() -> bool 是否是字母和数字组成
- isalpha() 是否是字母
- isdecimal() 是否只包含十进制数字
- isdigit() 是否全部数字(0~9)
- isidentifier() 是不是字母和下划线开头,其他都是字母、数字、下划线
- islower() 是否都是小写
- isupper() 是否全部大写
- isspace() 是否只包含空白字符

字符串格式化

format函数格式字符串语法——Python鼓励使用
 1. "{} {xxx}".format(*args, **kwargs) -> str
 2. args是位置参数,是一个元组
 3. kwargs是关键字参数,是一个字典
 4. 花括号表示占位符
 5. {}表示按照顺序匹配位置参数,{n}表示取位置参数索引为n的值 p {xxx}表示在关键字参数中搜索名称一致的
 6. {{}} 表示打印花括号

举栗子:
1.位置参数: "{}:{}".format('192.168.1.100',8888),这就是按照位置顺序用位置参数替换前面的格式字符串的占位符中
	>>> "{}:{}".format('192.168.1.100',8888)
	'192.168.1.100:8888'

2.关键字参数或命名参数: "{server} {1}:{0}".format(8888, '192.168.1.100', server='Web Server Info : ') ,位置参数按照序号匹配, 关键字参数按照名词匹配
	>>> "{server} {1}:{0}".format(8888, '192.168.1.100', server='Web Server Info : ')
	'Web Server Info :  192.168.1.100:8888'

3.访问元素: "{0[0]}.{0[1]}".format(('magedu','com'))
	>>> "{0[0]}.{0[1]}".format(('magedu','com'))
	'magedu.com'
4.对象属性访问: 
	>>> from collections import namedtuple
	>>> Point = namedtuple('Point','x,y')
	>>> p = Point(3,4)
	>>> p
	Point(x=3, y=4)
	>>> "{{{0.x},{0.y}}}".format(p)
	'{3,4}'

5.对齐格式化:
	>>> '{0}*{1}={2:<2}'.format(3,2,2*3)
	'3*2=6 '
	>>> '{0}*{1}={2:<02}'.format(3,2,2*3)
	'3*2=60'
	>>> '{0}*{1}={2:>02}'.format(3,2,2*3)
	'3*2=06'
	>>> '{:^30}'.format('centered')
	'           centered           '
	>>> '{:*^30}'.format('centered')
	'***********centered***********'	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值