内容正文:
《Python应用程序设计》
Python字符串的基本操作
计算机教科组
1
startswith( )
startswith( ):检查字符串是否以指定字符串开头,是则返回True,否则返回False.
startswith( )声明为: startswish(substr,[start [,end]])
口诀:指明头尾,头开始,尾-1
举例:
str="abcde"
print(str.startswith("ab")) #输出True
print(str.startswith("ab",0,1)) #False
print(str.startswith("ab",0,2)) #输出True
print(str.startswith("b",1,5)) #输出True
endswith( )
endswith( ):检查字符串是否以指定字符串结尾,是则返回True,否则返回False.
使用场景:常用于判断文件类型
startswith( )、 endswith( )中要查找的指定字符可以是单个字符,也可以是字符串,举例
str="abcde"
print(str.endswith("de")) #输出True
print(str.endswith("de",3,5)) #输出True
print(str.endswith("de",2,5)) #输出True
startswith( )/endswith( )
startswith( )、 endswith( )中要查找的指定字符还可以是元组
str = "i love python"
print(str.endswith(("n","z")))#遍历元组的元素,存在即返回True,否者返回False
课堂练习
1.表达式 'Beautiful'.startswith('Be', 5) 的值为?
2.表达式 'C:\Windows
otepad.exe'.startswith('C:') 的值为?
3.表达式 'C:\Windows
otepad.exe'.endswith('.exe') 的值为?
3.表达式 'test.py'.endswith(('.py', '.pyw')) 的值为?
4.表达式 'abc.txt'.endswith(('.txt', '.doc', '.jpg')) 的值为?
in运算符
in运算符用于检查集合的成员,需要两个参数:测试字符串和可能包含测试字符串的字符串。
形式如下: str1 in str2
如果测试字符串str1包含在str2中,且测试字符串序列必须完全相同则返回True,否则返回False。
举例:
print('rd' in 'word') #True
print('dr' in 'word') #False
list1=["apple","pear","banana"]
print("apple" in list1) #True
print("app" in list1) #False,因为list1只有三个元素,不含app,有apple
count()方法
count() 方法用于统计字符串里某个字符出现的次数
count()方法语法:str.count(sub, start,end)
口诀:指明头尾,头开始,尾-1
举例:
str="www.roob.com"
print(str.count('o')) #3
print(str.count("o",0,6)) #1
print(str.count("o",0,7)) #2
课堂练习
1. 表达式 ‘ab’ in ‘acbed’ 的值为?
2.表达式'apple'.count('p')的值为?
3.表达式'apple'.count('pp')的值为?
4.表达式'apple'.count('p',2)的值为?
5.表达式'apple'.count('p',1,4)的值为?
eval( ) 函数
eval(expression) 函数用来执行一个字符串表达式,并返回表达式的值
参数:expression -- 字符串表达式。
返回值:返回表达式计算结果。
如果处理的是数值型字符串,返回的数据类型是数值型。
举例:
print(eval(5)) #报错,TypeError: eval() 参数必须是字符串
print(eval("'123'")) #'123'
print(eval("ab")) #报错,NameError: 'ab' 未定义
eval( ) 函数
c=2**3
print(eval("c"))