1.2 基础数据类型 -- 字符串
1.字符串
字符串就是单个字符组成的集合. 字符串在基本数据类型中的数据类型关键字为str, 字符串属于序列的一种, 也就是组成字符串的每一个字符都是有顺序的, 我们通常把这种顺序称为索引. 字符串属于不可变数据类型. 在Python中使用单引号, 双引号或者三引号(三个单引号或三个双引号)来表示字符串, 如 'helloworld' , "hellopython" , '''Hello''' , """World"""
注: 单双引号可以交替使用, 解决一个字符串中含有单引号或双引号的问题, 如一个字符串” It’s me” . 三引号通常用于大段落的字符串, 可以自由换行.
2.字符串运算符
其中变量: a = "Hello" , 变量 b = "World"
操作符 | 操作符 | 示例 |
+ | 字符串拼接 |
>>>a + b HelloWorld |
* | 重复输出字符串 |
>>>a * 2 HelloHello |
[ ] | 通过索引获取字符串中字符 |
>>>a[0] H |
[:] | 截取字符串中的一部分 |
>>>a[0:2] He |
in | 成员运算符 - 如果字符串中包含给定的字符返回True |
>>>"H" in a True |
not in | 成员运算符 - 如果字符串中不包含给定的字符串返回False |
>>>"e" not in a False |
r/R | 原始字符串: 所有的字符串都是直接按照字面的意思来使用, me后转义特殊或不能打印的字符 |
>>>print r"\n" \n |
% | 格式字符串 | 详见下面 |
3.字符串的转义
转义字符 | 描述 |
\(在行尾时) | 续行符 |
\ | 反斜杠符号 |
\’ | 单引号 |
\” | 双引号 |
\a | 响铃 |
\b | 退格(Backspace) |
\e | 转义 |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车 |
\f | 换页 |
\oyy | 八进制数,yy代表的字符,例如:\o12代表换行 |
\xyy | 十六进制数,yy代表的字符,例如:\x0a代表换行 |
\other | 其它的字符以普通格式输出 |
4.字符串的格式化输出
(1).% 占位符法:常用的占位符有%s(字符串占位), %d(十进制数占位)
1 >>>a ="hello %s"%"world"
2 >>>print(a)
3 hello world
4 >>>b ="这件衣服价格为%d元"%50
5 >>>print(b)
6 这件衣服价格为50元
(2).format方法:相对%占位法, format更强大, format把字符串当做模板, 通过传入的参数进行格式化, 并且使用{ }作为特殊字符代替%.
(1)不带编号,即“{}”
(2)带数字编号,可调换顺序,即“{1}”、{2}”
(3)带关键字,即“(a)”、“tomy”
1 print('{} {}'.format('hello','world'))# 不带字段
2 output:hello world
3 print('{0} {1}'.format('hello','world'))# 带数字编号
4 output:hello world
5 print('{0} {1} {0}'.format('hello','world'))# 打乱顺序
6 output:hello world hello
7 print('{a} {tom} {a}'.format(tom='hello',a='world'))# 带关键字
8 output:world hello world
(3).format str格式化输出: f”str….{变量}…..”
1 name = input("请输入您的姓名:")# input获取到的字符串为:longbaby
2 print(f"您的姓名是:{name}")
3 output:
4 您的姓名是wusir
5.字符串常用的内置方法
(1) 大小写转换类:
1).str.title():各单词首字母转为大写
2).str.capitalize() :字符串首字母转为大写
3).str.upper():全部转换为大写
4).str.lower() :全部转换为小写
1 >>>s1 ="hello world"
2 >>>s2 ="AAA"
3 >>>print("title:", s1.title())
4 >>>print("capitalize:", s1.capitalize())
5 >>>print("upper", s1.upper())
6 >>>print("lower", s2.lower())
7 output:
8 HelloWorld
9 Hello world
10 HELLO WORLD
11 aaa
(2).统计与查找类:
1).str.count():统计指定字符在整个字符串中出现的次数
2).str.find() :查找指定字符在字符串中第一次出现的索引位置, 如果未查找到返回-1
3).str.index():查找指定字符在支付穿中第一次出现的索引位置, 如果未找到会抛出ValueError异常
1 >>>s ="Hello World"
2 >>>print(s.count('e'))
3 1# 字符串的索引从0开始
4 >>>print(s.find('e'))
5 2
6 >>>print(s.find("x"))
7 -1# 在s中未找到x字符, 返回-1
8 >>>str ="hello"
9 >>>print(str.index("l"))
10 2
11 >>>print(str.index("m"))
12 Traceback(most recent call last):# 未找到抛出了异常
13 File"<stdin>", line 1,in<module>
14 ValueError: substring not found
(3).编码解码类:
1).str.encode(“UTF-8”): 将字符串以utf-8进行编码
2).str.decode(“utf-8”): 对字符串以utf-8进行解码
(4).字符串分割:str.split()
1).将字符串应用特殊字符进行分割,并形成一个列表.
2).默认使用空格将字符串分割,如果定义该参数,则使用该参数进行分割,且字符串中包含的该参数将消失.
1 >>>str ="epythone"
2 >>>str_sp = str.split("e")
3 ["","python",""]
(5).脱去字符串收尾的指定字符:str.strip()
注:从字符串的首尾脱去参数parameter指定的特殊字符,如果未定义参数,默认脱去字符串收尾的空格.
1 >>>n1 =" hello " 2 >>>n2 ="123hello123"
3 >>>>print(n1.strip()) 4 hello
5 >>>print(n2.strip("123")) 6hello
(6).将字符串中的元素用指定字符进行连接:”-“.join(str)
1 >>>str ="hello"
2 >>>str_j ="-".join(str)
3 >>>print(str_j)
4 h-e-l-l-o
(7).字符串元素替换: str.replace(“oldstr”,”newstr”)
1 >>>alp ="abcd"
2 >>>alp= name.replace("a","b")
3 >>>print(alp)
4 bbcd
(8).判断字符串开头元素:str.starwith()
判断字符串结尾元素:str.endwith()
(9).字符串元素判断:is系列
- str.isalpha():判断字符串是不是纯字母
- str.isdigit():判断字符串是不是纯数字
- str.isalnum():判断字符串是不是字母和字符串的组合
- str.isspace():判断字符串是不是纯空格
- str.isupper():判断字符串是不是都是大写字母
- str.islower():判断字符串是不是都是小写字母
- str.isdecimal():是不是十进制字符
- str.isprintable():字符串是不是可打印
- str.isidentifiter:判断字符串