Python 字符串与序列
字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。
str1 = 'abc'
Python 访问字符串中的值
Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
Python 访问子字符串,可以使用方括号来截取字符串,如下实例:
>>> str2 = 'hello'
>>> str2[2:5]
'llo'
Python 字符串连接
我们可以对字符串进行截取并与其他字符串进行连接,如下实例:
>>> str1 = 'hello'
>>> str2 = 'world!'
>>> str1 + str2
'helloworld!'
Python 转义字符
在需要在字符中使用特殊字符时,python 用反斜杠 \ 转义字符。如下表:
转义字符 | 描述 |
---|---|
\(在行尾时) | 续行符 |
\\ | 反斜杠符号 |
\’ | 单引号 |
\" | 双引号 |
\b | 退格 |
\e | 转义 |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车 |
\f | 换页 |
Python 字符串格式化
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
>>> print("My name is %s and weight is %d kg!" % ('Zara', 21) )
My name is Zara and weight is 21 kg!
python 字符串格式化符号:
转义字符 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
python的字符串内建函数
方法 | 描述 |
---|---|
string.title() | 所有单词都是以大写开始,其余字母均为小写 |
string.capitalize() | 将第一个字符大写 |
string.lower() | 将字符串中字符小写化 |
string.upper() | 将字符串中字符大写化 |
string.swapcase() | 翻转 string 中的大小写 |
string.islower() | 如果字符串中所有字符都是小写则返回true |
string.isupper() | 如果字符串中所有字符都是大写则返回true |
string.lstrip() | 截掉 string 左边的空格 |
string.rstrip() | 删除 string 字符串末尾的空格 |
string.strip([obj]) | 删除字符串头尾空格 |
string.center(width) | 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 |
string.ljust(width) | 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串 |
string.rjust(width) | 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串 |
string.zfill(width) | 返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0 |
string.join(seq) | 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 |
string.count(str, beg=0, end=len(string)) | 统计字符串中str出现次数 |
string.find(str, beg=0, end=len(string)) | 检测 str 是否包含在 string 中 |
string.index(str, beg=0, end=len(string)) | 同find(),如果str不在 string中会报一个异常 |
string.encode(encoding=‘UTF-8’, errors=‘strict’) | 以encoding格式编码 |
string.decode(encoding=‘UTF-8’, errors=‘strict’) | 以encoding格式解码 |
>>> var_1 = '你好'
>>> encode_str = var_1.encode(encoding='UTF-8', errors='strict')
>>> encode_str.decode(encoding='UTF-8', errors='strict')
'你好'
>>> encode_str
b'\xe4\xbd\xa0\xe5\xa5\xbd'