字符串的定义
- 字符串 就是 一串字符,是编程语言中表示文本的数据类型
- 在 Python 中可以使用 一对双引号 " 或者 一对单引号 ' 定义一个字符串
- 虽然可以使用
\"
或者\'
做字符串的转义,但是在实际开发中:- 如果字符串内部需要使用 ":,可以使用 ' 定义字符串,例如:'lian "hello" '
- 如果字符串内部需要使用 ',可以使用 " 定义字符串
- 虽然可以使用
- 可以使用 索引 获取一个字符串中 指定位置的字符,索引计数从 0 开始
- 也可以使用
for
循环遍历 字符串中每一个字符 - 避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用
.join
连接列表. (也可以将每个子串写入一个cStringIO.StringIO
缓存中.) -
字符串的常用操作
- 切片:字符串最后一位索引为-1。
- 语法:
变量名[起始索引:终止索引,步长]
例子
>>> test = "hello world"
>>> print(test[2:-3:1])
llo wo
>>>
2.搜索
- index()搜索字符串的位置
- rindex()从右边搜索字符串的位置
- find()搜索字符串的位置
- rfind()从右边搜索字符串的位置
返回目标字符的索引。
注意:如果搜索字符不存在,index会抛出异常,而find会返回索引-1
例子:
>>> print(test.index("l",2))
4
>>> print(test.find("l",2))
4
>>> print(test.index("kkkkk",2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> print(test.find("kkkkk",2))
-1
>>>
3.统计
- len()计算字符串长度
- count()统计子串出现次数
- 例子
>>> test = "hello ,@@@@@world@@@@@"
>>> print(len(test))
22
>>> print(test.count("@"*5))
2
>>>
4.判断字符串内容
- isalnum() 判断字符串是否全为数字或字母组合而成的
- isalpha()判断字符串是否全为字母
- isdigit()判断字符串是否全为数字
- isdecimal()判断字符串是否全为数字
- isnumeric()判断字符串是否全为数字
- isspace() 判断是否只含空格
- istitle()判断字符串每个单次的首字母是否大写
- islower()判断所有字符是否均为小写
- isupper()判断所有字符是否均为大写
- isprintable()判断所有字符是否都是可打印字符。(repr()打印范围:Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符(但不包括ASCII码中的空格(0x20)。可用于判断转义字符。ASCII码中第0~32号及第127号是控制字符;第33~126号是可打印字符,其中第48~57号为0~9十个阿拉伯数字;65~90号为26个大写英文字母,97~122号为26个小写英文字母。)
- isidentifier()判断字符串是否符合变量命名标准
- 例子
-
>>> t1 = "123" >>> print(t1.isdigit(),t1.isalpha(),t1.isalnum()) (True, False, True) >>> t2 = "abc" >>> print(t2.isdigit(),t2.isalpha(),t2.isalnum()) (False, True, True) >>> t3 = "ab12c3" >>> print(t3.isdigit(),t3.isalpha(),t3.isalnum()) (False, False, True) >>>
5.大小写转换
- capitalize() 字符串首字母大写
- lower()所有字母转为小写
- casefold()所有字母转为小写
- upper()所有字母转为大写
- swapcase()字符串大小写倒置
- title()字符串标题化,所有单次首字母大写
- 例子
>>> name = "hello World-----||||" >>> print(name.capitalize(),name.lower(),name.casefold(),name.upper(),name.swapcase(),name.title()) Hello world-----|||| hello world-----|||| hello world-----|||| HELLO WORLD-----|||| HELLO wORLD-----|||| Hello World-----|||| >>>
6.对齐方式
- center(width,fillchar) 元字符串居中,字符串扩展成长度为width,左右不足用fillchar补充
- ljust(width,fillchar)左对齐,字符串扩展成长度为width,右不足用fillchar补充
- rjust(width,fillchar)右对齐,字符串扩展成长度为width,左不足用fillchar补充
7.分割
- split(sep=None, maxsplit=-1)以字符sep作为分割线,最多分成maxspilt份,返回列表
- splitlines()按照行("\r","\n","\r\n")分割,返回列表
- partition(sep)以字符sep作为分割符,分成3份(不足用空白代替),返回元组
- rpartition(sep)从右边开始以字符sep作为分割符,分成3份(不足用空白代替),返回元组
- 例子
-
>>> name = "little-five-hello-world" >>> print(name.partition("-"),name.split("-",9)) ('little', '-', 'five-hello-world') ['little', 'five', 'hello', 'world'] >>>
8.判断以什么开头结尾
- startswith()判断以什么开头
- endswith()判断以什么结尾
9.拼接
- +:最简单的字符串拼接方式,但是性能较差
- join():性能较好的字符串拼接方式
10.翻译
- maketrans() 创建字符串与字符串之间的对应关系,字符是一个对应一个,字符串长度必须一致,相同字符的关系会覆盖。
- translate()通过定义好的字符串对应关系进行关系翻译。
>>> a = "wss"
>>> b = "我是谁"
>>> info = str.maketrans(a,b)
>>> print("wss?我是连".translate(info))
我谁谁?我是连
11.格式化输出
- format()格式化字符串
- format_map()格式化字符串
>>> info = "my name is {name},I'am {age} years old."
>>> print(info.format(name="lian",age=20))
my name is lian,I'am 20 years old.
>>> print(info.format(**{"name":"lian","age":20}))
my name is lian,I'am 20 years old.
>>> print(info.format_map({"name":"lian","age":20}))
my name is lian,I'am 20 years old.
>>> info = "my name is {0},I'am {0} years old."
>>> print(info.format("lian",20))
my name is lian,I'am 20 years old.
12.其它
- replace()替换字符串
- strip()清除指定字符串,默认空格
- lstrip()清除左边指定字符串,默认空格
- rstrip()清除右边指定字符串,默认空格
- expandtabs()返回字符串中的 tab 符号('\t')转为空格后生成的新字符串。通常可用于表格格式的输出
以上为Str文档全部内置操作函数,详细参数请查看文档!