6.1 处理字符串
6.1.1 字符串字面量
Python默认是单引号开始,单引号结束。
如何在字符串中使用单引号呢 ?如下,使用双引号 或者 转义字符
6.1.2 使用双引号
1 >>> spam = "this is Alice‘s cat" 2 >>> spam 3 "this is Alice‘s cat"
6.1.3 转义字符
1 >>> spam = ‘this is Alice\‘s cat‘ 2 >>> spam 3 "this is Alice‘s cat"
常用转义字符
转义字符 打印为 \‘ ‘
\" "
\t 制表符
\n 换行符
\\ \
6.1.4 原始字符串
在字符串之前加上r
>>> spam = r‘this is Alice\‘s cat‘ >>> spam "this is Alice\\‘s cat" >>> print(spam) this is Alice\‘s cat >>>
6.1.5 用三重引号的多行字符串
多行字符串的起止是 三个 单引号 或 双引号。
三重引号之间的所有引号、换行符、回车符 都是字符串的一部分,其中的特殊字符不需要转义。
>>> spam = """ hello huahua, this is huihui‘s toy, it costs 13$, so don‘t touch it ,OK ? """ >>> spam "\nhello huahua,\nthis is huihui‘s toy, it costs 13$, so\ndon‘t touch it ,OK ?\n" #实际存储形式 >>> print(spam) # 打印形式 hello huahua, this is huihui‘s toy, it costs 13$, so don‘t touch it ,OK ?
6.1.6 多行注释
# 单行注释
三重引号:多行注释
6.1.7 字符串下表和切片
字符串可以看做是由单个字符组成的列表,每个字符都是列表的表项。
6.1.8 字符串的in 和 not in 操作符
6.2 有用的字符串方法
6.2.1 upper(), lower(), isupper(), islower()
字符串至少含有一个字母,并且所有的字母都是大写或者小写,isupper() islower()才返回True
6.2.2 isX方法
6.2.3 字符串方法 startswith() 和 endswith()
6.2.4 字符串方法 join() 和 split()
join用法: 分隔符.join([列表项])
>>> ‘ ‘.join([‘my‘,‘name‘,‘is‘,‘huahua‘]) ‘my name is huahua‘
split用法:待分割字符串.split(分隔符)
>>> ‘my-name-is-huahua‘.split(‘-‘)
[‘my‘, ‘name‘, ‘is‘, ‘huahua‘]
6.2.5 用rjust(), ljust() 和 center()方法对齐文本
1 >>> ‘huahua‘.rjust(20, ‘#‘) 2 ‘##############huahua‘ 3 >>> ‘huahua‘.ljust(20,‘#‘) 4 ‘huahua##############‘
6.2.6 strip() rstrip() lstrip()删除单侧/双侧空白字符
strip() 有可选字符串参数,用于删除两侧/单侧特定字符
>>> ‘555adfasdaf555‘.strip(‘555‘) ‘adfasdaf‘
原文:https://www.cnblogs.com/wooluwalker/p/11624218.html