立即学习:https://edu.csdn.net/course/play/24797/282156?utm_source=blogtoedu
★ 本节目标
- 转义字符
- 字符串格式化 (重点、难点)
- 调用函数(方法)操作字符串(重点)
★ 转义字符
如果字符串本身包含反斜线,则需要使用\\表示,其中\\就是转义字符。
s = 'a\tb\tc'
print(s)
s2 = 'a\nb\nc'
print(s2)
★ 字符串格式化
使用%加转换说明符的方式执行字符串格式化,Python支持如下所示转换说明符。
s = '我爱%s'
print(s % 'Python')
#s2先转成str,d代表十进制整数
s2 = '我最爱的图书是%s,价格是%d'
print(s2 % ('疯狂Python讲义' , 128))
price = 128
s3 = '价格是%d , 八进制为:%o , 十六进制为:%x , 字符串形式为:%r'
print(s % (price , price ,price , price) )
★ 序列相关的方法
- 字符串本质就是由多个字符组成,字符串的本质就是不可变序列,因此序列相关的方法:
- 基于索引的计算
- in运算
- len()函数
- min()、max()函数
s = 'fkjava.org'
#根据下标访问
print(s[3])
#指定开始、结束
print(s[2 : 4])
#指定开始、结束、步长
print(s[2 : 6 : 3])
print('org' in s) # True
print('ork' in s) # False
print('s字符串的长度为:' , len(s))
print(max(s)) # v
print(min(s)) # .
#字符串的方法
print(s.upper()) # FKJAVA.ORG
print(s.title()) # Fkjava.Org
print(s.lower()) # fkjava.org
#dir可以查看某个类的所有方法
print(s.islower())
★ 大小写相关的方法
- title():将每个单词首字母改为大写。
- lower():将整个字符串改为小写。
- upper():将整个字符串改为大写。
dir()可以查看某个类的所有方法。
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__'
, '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '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', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
#使用help命令可以查看某个方法的具体用法
>>> help(str.islower)
Help on method_descriptor:
islower(self, /)
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
★ 删除空白
- strip():删除字符串前后的空白
- lstrip():删除字符串前面(左边)的空白。
- rstrip():删除字符串后面(右边)的空白。
s = ' fkjava.org '
print(s.strip())
print(s.lstrip())
print(s.rstrip())
★ 查找、替换相关方法
- startswith():判断字符串是否以指定子串开头。
- endswith():判断字符串是否以指定子串结尾。
- find():查找指定子串在字符串中的出现位置,如果没有找到指定子串,则返回-1。
- index():查找指定子串在字符串中的出现位置,如果没有找到指定子串,则引发ValueError错误。
- replace():使用指定子串替换字符串中的目标子串。
- translate():使用指定的翻译映射表对字符串执行替换。
s = 'fkjava.org'
print(s.find("ava")) #3
print(s.find("aja")) #-1
★ 分割、连接
- split():将字符串按指定分隔符分割成多个短语。
- join():将多个短语连缀成字符串。
s = 'www.fkjava.org'
print(s.split('.')) #['www', 'fkjava', 'org']
print('='.join(s.split("."))) #www=fkjava=org
★ 本节小结
- 转义字符
- 字符串格式化
- 字符串相关函数和方法