Bridge619

Bridge619

Bridge619

命定的局限尽可永在,不屈的挑战却不可须臾或缺!

101 文章数
11 评论数
来首音乐
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

Python字符串及其常用操作

Bridge619
2022-08-03 / 0 评论 / 544 阅读 / 0 点赞

1. 字符串的定义

  • 字符串 就是 一串字符,是编程语言中表示文本的数据类型
  • 在 Python 中可以使用 一对双引号 " 或者 一对单引号 ' 定义一个字符串
  • 虽然可以使用 \" 或者 \' 做字符串的转义,但是在实际开发中:
    • 如果字符串内部需要使用 `"`,可以使用 `'` 定义字符串
    • 如果字符串内部需要使用 `'`,可以使用 `"` 定义字符串
  • 可以使用 索引 获取一个字符串中 指定位置的字符,索引计数从 0 开始
  • 也可以使用 for 循环遍历 字符串中每一个字符

大多数编程语言都是用 " 来定义字符串

string = "Hello Python"

for c in string:
    print(c)
Out:
H
e
l
l
o

P
y
t
h
o
n

2. 字符串的常用操作

  • ipython3 中定义一个 字符串,例如:hello_str = ""
  • 输入 hello_str. 按下 TAB 键,ipython 会提示 字符串 能够使用的 方法 如下:
In [1]: hello_str.
hello_str.capitalize    hello_str.isidentifier  hello_str.rindex
hello_str.casefold      hello_str.islower       hello_str.rjust
hello_str.center        hello_str.isnumeric     hello_str.rpartition
hello_str.count         hello_str.isprintable   hello_str.rsplit
hello_str.encode        hello_str.isspace       hello_str.rstrip
hello_str.endswith      hello_str.istitle       hello_str.split
hello_str.expandtabs    hello_str.isupper       hello_str.splitlines
hello_str.find          hello_str.join          hello_str.startswith
hello_str.format        hello_str.ljust         hello_str.strip
hello_str.format_map    hello_str.lower         hello_str.swapcase
hello_str.index         hello_str.lstrip        hello_str.title
hello_str.isalnum       hello_str.maketrans     hello_str.translate
hello_str.isalpha       hello_str.partition     hello_str.upper
hello_str.isdecimal     hello_str.replace       hello_str.zfill
hello_str.isdigit       hello_str.rfind

提示:正是因为 python 内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作!应对更多的开发需求!

1) 判断类型 - 9

方法 说明
string.isspace() 如果 string 中只包含空白字符,则返回 True
string.isalnum() 如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True
string.isalpha() 如果 string 至少有一个字符并且所有字符都是字母则返回 True
string.isdecimal() 如果 string 只包含数字则返回 True,全角数字
string.isdigit() 如果 string 只包含数字则返回 True,全角数字unicode字符串、\u00b2
string.isnumeric() 如果 string 只包含数字则返回 True,全角数字汉字数字
以上这三个判断数字的方法从上到下范围越来越大,但是都不能判断小数
string.istitle() 如果 string 是标题化的(每个单词的首字母大写)则返回 True
string.islower() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True
string.isupper() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True

2) 查找和替换 - 7

方法 说明
string.startswith(str) 检查字符串是否是以指定字符串 str 开头,是则返回 True
string.endswith(str) 检查字符串是否是以指定字符串 str 结束,是则返回 True
string.find(str, start=0, end=len(string)) 检测 str 是否包含在 string 中,如果 start 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回 -1
string.rfind(str, start=0, end=len(string)) 类似于 find(),不过是从右边开始查找
string.index(str, start=0, end=len(string)) 跟 find() 方法类似,不过如果 str 不在 string 会报错
string.rindex(str, start=0, end=len(string)) 类似于 index(),不过是从右边开始
string.replace(old_str, new_str, num=string.count(old)) 把 string 中的 old_str 替换成 new_str,如果 num 指定,则替换不超过 num 次,replace方法执行后会返回一个新的字符串

3) 大小写转换 - 5

方法 说明
string.capitalize() 把字符串的第一个字符大写
string.title() 把字符串的每个单词首字母大写
string.lower() 转换 string 中所有大写字符为小写
string.upper() 转换 string 中的小写字母为大写
string.swapcase() 翻转 string 中的大小写

4) 文本对齐 - 3

方法 说明
string.ljust(width) 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
string.rjust(width) 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

5) 去除空白字符 - 3

方法 说明
string.lstrip() 截掉 string 左边(开始)的空白字符
string.rstrip() 截掉 string 右边(末尾)的空白字符
string.strip() 截掉 string 左右两边的空白字符

6) 拆分和连接 - 5

方法 说明
string.partition(str) 把字符串 string 分成一个 3 元素的元组 (str前面, str, str后面)
string.rpartition(str) 类似于 partition() 方法,不过是从右边开始查找
string.split(str="", num) 以 str 为分隔符拆分 string,如果 num 有指定值,则仅分隔 num + 1 个子字符串,str 默认包含 '\r', '\t', '\n' 和空格
string.splitlines() 按照行('\r', '\n', '\r\n')分隔,返回一个包含各行作为元素的列表
string.join(seq) 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串

3. 字符串的切片

  • 切片 方法适用于 字符串列表元组
  • 切片 使用 索引值 来限定范围,从一个大的 字符串切出 小的 字符串
  • 列表元组 都是 有序 的集合,都能够 通过索引值 获取到对应的数据
  • 字典 是一个 无序 的集合,是使用 键值对 保存数据
字符串[开始索引:结束索引:步长]

注意

  1. 指定的区间属于 左闭右开[开始索引, 结束索引) => 开始索引 >= 范围 < 结束索引
  • 起始 位开始,到 `结束`位的前一位 结束(不包含结束位本身)
  1. 从头开始,开始索引 数字可以省略,冒号不能省略
  2. 到末尾结束,结束索引 数字可以省略,冒号不能省略
  3. 步长默认为 1,如果连续切片,数字和冒号都可以省略

索引的顺序和倒序

  • 在 Python 中不仅支持 顺序索引,同时还支持 倒序索引
  • 所谓倒序索引就是 从右向左 计算索引
  • 最右边的索引值是 -1,依次递减
  • 例如:
num_str ='012345'
num_str[0::-1]
#表示从0开始向右取,-1表示步长为1向右取,则结果为0
#所以逆序就可以为num_str[::-1]

4.Python转义字符

在需要在字符中使用特殊字符时,python 用反斜杠 ** 转义字符。如下表:

转义字符 描述 实例(>>>:输出)
(在行尾时) 续行符 print("line1 \ ... line2 \ ... line3")
Out:line1 line2 line3
\ 反斜杠符号 print("\\")
\
\' 单引号 print('\'')
'
\" 双引号 print("\"")
"
\a 响铃 print("\a")
执行后电脑有响声。
\b 退格(Backspace) print("Hello \b World!")
Hello World!
\000 print("\000")
\n 换行 print("\n")
\v 纵向制表符 print("Hello \v World!")
Hello
World!
\t 横向制表符 print("Hello \t World!")
Hello World!
\r 回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成。 print("Hello\rWorld!")
World!
print('google runoob taobao\r123456')
123456 runoob taobao
\f 换页 print("Hello \f World!")
Hello
World!
\yyy 八进制数,y 代表 0~7 的字符,例如:\012 代表换行。 print("\110\145\154\154\157\40\127\157\162\154\144\41")
Hello World!
\xyy 十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行 print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
Hello World!
\other 其它的字符以普通格式输出

5.Python 字符串格式化

Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。

在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。

实例(Python 3.0+)

#!/usr/bin/python3 print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

以上实例输出结果:

我叫 小明 今年 10 岁!

python字符串格式化符号:

符 号 描述
%c 格式化字符及其ASCII码
%s 格式化字符串
%d 格式化整数
%u 格式化无符号整型
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同%e,用科学计数法格式化浮点数
%g %f和%e的简写
%G %f 和 %E 的简写
%p 用十六进制数格式化变量的地址

格式化操作符辅助指令:

符号 功能
* 定义宽度或者小数点精度
- 用做左对齐
+ 在正数前面显示加号( + )
在正数前面显示空格
# 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0 显示的数字前面填充'0'而不是默认的空格
% '%%'输出一个单一的'%'
(var) 映射变量(字典参数)
m.n. m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

文章不错,扫码支持一下吧~
上一篇 下一篇
评论