重点:字符串,容器类型公共方法
时间:2019年12月18日
课程:黑马Python基础20、21章(185.1~192.8)
20.字符串
185.1 字符串的定义和基本使用
- 字符串 就是 一串字符,是编程语言中表示文本的数据类型
- 在 Python 中可以使用 一对双引号
"
或者 一对单引号'
定义一个字符串- 虽然可以使用
\"
或者\'
做字符串的转义,但是在实际开发中:- 如果字符串内部需要使用
"
,可以使用'
定义字符串 - 如果字符串内部需要使用
'
,可以使用"
定义字符串
- 如果字符串内部需要使用
- 虽然可以使用
- 可以使用 索引 获取一个字符串中 指定位置的字符,索引计数从 0 开始
- 也可以使用
for
循环遍历 字符串中每一个字符
大多数编程语言都是用
"
来定义字符串
05-高级数据类型,hm-14-字符串定义
string = "Hello Python"
for c in string:
print(c)
186.2 字符串长度、计算、位置方法演练
05-高级数据类型,hm-15-字符串统计操作
hello_str = "hello hello"
# 1. 统计字符串长度
print(len(hello_str))
# 2. 统计某一个小字符串出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))
# 3. 某一个子字符串出现的位置
print(hello_str.index("llo"))
# 注意:如果使用index方法传递的子字符串不存在,程序会报错!
print(hello_str.index("abc"))
187.3 常用方法纵览和分类
- 在
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 内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作!应对更多的开发需求!
image.png
image.png
image.png
image.png
188.4 判断空白字符以及学习方法分享
05-高级数据类型 hm-16-字符串判断方法
# 1. 判断空白字符
space_str = " \t\n\r"
print(space_str.isspace())
189.5 判断数字的三个方法
05-hm-16
# 2. 判断字符串中是否只包含数字
# 1> 都不能判断小数
# num_str = "1.1"
# 2> unicode 字符串
# num_str = "\u00b2"
# 3> 中文数字
num_str = "一千零一"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
190.6 字符串的查找和替换
05-hm-17
hello_str = "hello world"
# 1. 判断是否以指定字符串开始
print(hello_str.startswith("Hello"))
# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))
# 3. 查找指定字符串
# index 同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("llo"))
# index 如果指定的字符串不存在,会报错
# find 如果指定的字符串不存在,会返回-1
print(hello_str.find("abc"))
# 4. 替换字符串
# replace方法执行完成之后,会返回一个新的字符串
# 注意:不回修改原有字符串的内容
print(hello_str.replace("world", "python"))
print(hello_str)
191.7 文本对齐方法演练
05-hm-18
# 假设:以下内容是从网络上抓取的
# 要求:顺序并且居中对齐输出以下内容
poem = ["登鹳雀楼",
"王之涣",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str in poem:
print("|%s|" % poem_str.ljust(10, " "))
192.8 去除空白字符
string.lstrip()
截掉 string 左边(开始)的空白字符
string.rstrip()
截掉 string 右边(末尾)的空白字符
string.strip()
截掉 string 左右两边的空白字符
网友评论