字符串对象
字符串在Python中时基本数据类型:
单引号
双引号
三引号
在Python中,字符创不仅仅是基本数据类型,也是一种对象
>>> s = "hello"
>>> dir(s)
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
函数 | 作用 |
---|---|
capitalize() | 将字符串首字母转为大写 |
center() | 居中对齐 |
ljust() | 左对齐 |
rjust() | 右对齐 |
endswith() | 是否以xxx结尾 |
startwith() | 是否以xxx开始 |
format() | 格式化字符串 |
index() | 返回参数的下标(参数含多个字符,会报错) |
rindex() | 同上,从右向左找 |
find() | 返回参数的下标(参数含多个字符,返回-1) |
rfind() | 同上,从右向左找 |
replace() | 替换字符串 |
count() | 统计字符串的数量 |
upper() | 转换成大写 |
lower() | 转换成小写 |
strip() | 清除字符串两侧空格 |
title() | 转成标题格式(每个单词首字母大写) |
istitle() | 是否符合标题格式 |
isalnum() | 是否是字母或者数字 |
… | |
encode() | 将字符串编码为字节数据(重要) |
decode | 字节对象的方法 |
translate()和maketrans()组合可以做移位加密
>>> s.center(30)
' hello '
>>> s.center(30, "+")
'++++++++++++hello+++++++++++++'
>>> s.rjust(30)
' hello'
>>> s.rjust(30, "+")
'+++++++++++++++++++++++++hello'
>>> s.endswith("llo")
True
>>> s.startswith("hel")
True
>>> s
'hello'
>>> s.encode()
b'hello'
>>> type(s)
<class 'str'>
>>> aa = s.encode()
>>> type(aa)
<class 'bytes'>