Python数据类型-字符串类型
<p>1、特点</p>
<pre><code>1.1、字符串一旦定义不允许修改,可以替换。字符串容器中的元素都是字符类型的。
1.2、字符串是一个不可修改的序列,当我们对字符串进行修改的时候,实际上是生成了一个新的被修改后的对象,而原字符串没有发生修改。
1.3、字符串开始和结尾使用的引号形式必须一致。
1.4、当表示复杂的字符串时,还可以进行引号的嵌套。
例如:
"a'bb'c"、""" aa'bb'cc"dd"ee """</code></pre>
<p>2、定义</p>
<pre><code>str = 'hello world'
2.1、字符串是一个有序的,不可修改的,元素以引号包围的序列。
2.2、字符串的定义:
'x' #使用单引号,字符串内容必须在一行中。
"x" #使用单引号,字符串内容必须在一行中。
'''x''' #使用三单引号,字符串内容可以换行。
''''''x'''''' #使用三单引号,字符串内容可以换行。
2.3、单引号和双引号需要区分着来用,以下这种情况,需要使用双引号,单引号会报错。
print('yours's dog')->会报错
print("yours's dog")->正常</code></pre>
<p>3、循环遍历</p>
<pre><code>str = 'hello world'
for i in range(0, len(str)):
print(str[i], end='')
# 结果:hello world
for i in str:
print(i,end='')
# 结果:hello world</code></pre>
<p>4、转义字符</p>
<pre><code>4.1、python中字符串还支持转义字符,详见[转义字符]。
4.2、在字符串定界符引号前面加上r或R,那么该字符将原样输出,其中转义字符将不进行转义。
例如:
>>> print("学海无涯\x0a苦作舟")
学海无涯
苦作舟
>>> print(r"学海无涯\x0a苦作舟")
学海无涯\x0a苦作舟</code></pre>
<p>5、字符串的索引</p>
<pre><code>5.1、说明
字符串的索引(index)-在python当中所有有序的序列都是由索引概念的,但是区别在于序列可不可以被修改。索引在我们初学的时候我们可以理解为字符串的下标,字符串里的每一个个体都被称作字符也是该字符串的一个元素。
字符串——“hello”
h e l l o
0 1 2 3 4 正索引
-5 -4 -3 -2 -1 负索引
5.2、索引的用法-1
(1)取单个元素
字符串[索引值]——>对应索引值的元素
print("hello"[1]) 输出:e
(2)截取
字符串[start:end]——>得到对应范围的元素,该范围包含起始端,不包含结尾端,默认截取的方向是从左往右的。
print("hello"[1:3]) 输出:el
(3)步长截取
字符串[start:end:step] 按照步长减一进行隔取
print("whileisok"[0:7:3]) 输出:wls
(4)默认取法
字符串[start:end,step]——>这三个参数都有默认值: Start 0;End 结尾;Step 1
print("whileisok"[:7]) 输出:whileis
print("whileisok"[0:]) 输出:whileisok
(5)反取
字符串[负数]——>从右往左取
print("whileisok"[-1]) 输出:k
print("whileisok"[-3]) 输出:s
print("whileisok"[::-1]) 输出:kosielihw
5.3、索引的用法-2
(1)访问/通过表名+引索
print(str[4])
结果:o /打印下标索引为4的字符
print(str[2:])
结果:llo world /打印下标索引为2后面的字符
print(str[:2])
结果:he /打印下标索引为2前面的字符
print(str[2:5])
结果:llo /打印下标索引为2-5之间的字符
print(str[:])
结果:hello world /打印str所有数据
print(str)
结果:hello world /打印str所有数据
print(str * 2)
结果:hello world hello world /输出字符串两次
print(str + "TEST" )
结果:hello worldTEST /输出连接的字符串
5.4、总结
str = 'hello'
用法1——>print("hello"[1]) 输出:e
用法2——>print(str[1]) 输出:e</code></pre>
<p>6、字符串的修饰</p>
<pre><code>6.1、Center
让字符串在指定的长度居中,如果不能居中左短右长,可以指定填充内容,默认以空格填充。
print("while".center(10)) #让while在10个长度里居中
print("while".center(10,"*")) #让while在10个长度里居中,空白的地方以*填充
print(len("while")) #打印"while"本身的长度
print(len("while".center(10))) #打印"while".center(10)的长度
输出:
while
**while***
5
10
6.2、ljust
让字符串在指定的长度左齐,如果不能居中左短右长,可以指定填充内 容,默认以空格填充。
print("while".ljust(10))
print("while".ljust(10,"*"))
输出:
while
while*****
6.3、rjust
让字符串在指定的长度右齐,如果不能居中左短右长,可以指定填充内 容,默认以空格填充。
print("while".rjust(10))
print("while".rjust(10,"*"))
输出:
while
*****while
6.4、zfill
将字符串填充到指定的长度,不足地方用0从左开始补充。
print("while".zfill(10))
输出:
00000while
6.5、format
按照顺序,将后面的参数传递给前面的大括号。
print("{} is {} years old".format("while",18))
输出:
while is 18 years old
6.6、strip
默认去除两边的空格,去除内容可以指定。
print(" while hello ".strip())
输出:
while hello
#=================================
print("***while*hello***".strip())
输出:
***while*hello***
#=================================
print("***while*hello***".strip("*"))
输出:
while*hello
#=================================
6.7、rstrip
默认去除右边的空格,去除内容可以指定。
print(" while hello ".rstrip())
输出:
while hello
#=================================
print("***while*hello***".rstrip())
输出:
***while*hello***
#=================================
print("***while*hello***".rstrip("*"))
输出:
***while*hello
6.8、lstrip
默认去除左边的空格,去除内容可以指定。
print(" while hello ".lstrip())
输出:
while hello
#=================================
print("***while*hello***".lstrip())
输出:
***while*hello***
#=================================
print("***while*hello***".lstrip("*"))
输出:
while*hello***</code></pre>
<p>7、字符串的查找</p>
<pre><code>7.1、count
计数功能,返回自定字符在字符串当中的个数。
print("hello world".count("l"))
输出:
3
7.2、find
查找,返回从左第一个指定字符的索引,找不到返回-1。
print("hello world".find("l"))
输出:
1
# ==============================
print("hello world".find("q"))
输出:
-1
7.3、rfind
查找,返回从右第一个指定字符的索引,找不到返回-1。
print("hello world".rfind("l"))
输出:
9
# ==============================
print("hello world".rfind("q"))
输出:
-1
7.4、index
查找,返回从左第一个指定字符的索引,找不到报错。
print("hello world".index("l"))
输出:
2
# ==============================
print("hello world".index("q"))
输出:
ValueError: substring not found
7.5、rindex
查找,返回从右第一个指定字符的索引,找不到报错。
print("hello world".rindex("l"))
输出:
9
# ==============================
print("hello world".rindex("q"))
输出:
ValueError: substring not found</code></pre>
<p>8、字符串的替换</p>
<pre><code>8.1、replace
从左到右替换指定的元素,可以指定替换的个数,默认全部替换。
print("hello world".replace("l","2"))
输出:
he22o wor2d
# ==============================
print("hello world".replace("l","2",2))
输出:
he22o world
8.2、translate
按照对应关系来替换内容。
from string import maketrans
trans = maketrans("12345","abcde")
print("12123123".translate(trans))
输出:
ababcabc</code></pre>
<p>9、字符串的变形</p>
<pre><code>9.1、upper
将字符串当中所有的字母转换为大写,如果有大写的,将会保留不变。
print("while is ok 1992".upper())
输出:
WHILE IS OK 1992
===================================
print("while is Ok 1992".upper())
输出:
WHILE IS OK 1992
9.2、lower
将字符串当中所有的字母转换为小写 ,如果有大写的,将会保留不变。
print("WHILE iS OK 1992".lower())
输出:
while is ok 1992
9.3、swapcase
将字符串当中所有的字母大小写互换。
print("WHIle iS OK 1992".swapcase())
输出:
whiLE Is ok 1992
9.4、title
将字串符当中的单词首字母大写,单词以空格划分。
print("WHIle iS ok 1992 a bc D".title())
输出:
While Is Ok 1992 A Bc D
9.5、capitalize
只有字符串的首字母大写。
print("WHIle iS ok 1992".capitalize())
输出:
While is ok 1992
9.6、expandtabs
修改\t的长度。
print("while is ok 1992".expandtabs())
print("while \t is ok 1992".expandtabs())
print("while \t is ok 1992".expandtabs(16))
输出:
while is ok 1992
while is ok 1992
while is ok 1992</code></pre>
<p>10、字符串的判断</p>
<pre><code>10.1、isalnum
判断字符串是否完全由字母和数字组成。
print("hello world".isalnum())
print("hello 123".isalnum())
print("hello123".isalnum())
输出:
False
False
True
10.2、isalpha
判断字符串是否完全由字母组成。
print("hello world".isalpha())
print("helloworld".isalpha())
print("hello 123".isalpha())
输出:
False
True
False
10.3、isdigit
判断字符串是否完全由数字组成。
print("123456".isdigit())
print("12 3".isdigit())
print("hello123".isdigit())
输出:
True
False
False
10.4、isupper
判断字符串当中的字母是否完全是大写。
print("hello".isupper())
print("HELLO".isupper())
print("helLO".isupper())
输出:
False
True
False
10.5、islower
判断字符串当中的字母是否完全是小写。
print("hello".islower())
print("HELLO".islower())
print("helLO".islower())
输出:
True
False
False
10.6、istitle
判断字符串是否满足title格式 ,title格式 是指-只有单词的首字母大写。
print("hello".istitle())
print("HELLO".istitle())
print("helLO".istitle())
print("Hello".istitle())
输出:
False
False
False
True
10.7、isspace
判断字符串是否完全由空格组成。
print(" ".isspace())
print(" a ".isspace())
print(" \t ".isspace())
print(" \n ".isspace())
输出:
True
False
True
True
10.8、startswith
判断字符串的开头字符,也可以截取判断。
print("hello world".startswith("h")) #判断字符串的开始是不是"h"
print("hello world".startswith("e")) #判断字符串的开始是不是"e"
print("hello world".startswith("e",1)) #判断字符串下标从1开始的是不是"e"
print("hello world".startswith("e",1,3)) #判断字符串下标从1-3开始的是不是"e"
输出:
True
False
True
True
10.9、endswith
判断字符串的结尾字符,也可以截取判断。
print("hello world".endswith("d")) #判断字符串的结尾是不是"d"
print("hello world".endswith("w",1,6)) #判断字符串从1-6的结尾是不是"w"
print("hello world".endswith(" ",1,6)) #判断字符串从1-6的结尾是不是" "
输出:
True
False
True</code></pre>
<p>11、字符串的切分</p>
<pre><code>11.1、以行切分字符串
方法
splitlines()
说明
以行切分字符串,可以指定是否保留行标志(这里0和1代表的是布尔值)。
案例
print(
"""
hello world
hello kerulu
""".splitlines()
)
输出:
['', ' hello world', ' hello kerulu', ' ']
===================================================
print(
"""
hello world
hello kerulu
""".splitlines(0)
)
输出:
['', ' hello world', ' hello kerulu', ' ']
===================================================
print(
"""
hello world
hello kerulu
""".splitlines(1)
)
输出:
['\n', ' hello world\n', ' hello kerulu\n', ' ']
===================================================
print("hello world".splitlines())
输出:
['hello world']
11.2、从左开始切分字符串
方法
split()
说明
从左开始切分字符串,可以指定切分次数和对象 ,默认以空格切割。
案例
print("hello world ke ru lu".split())
print("hello world ke ru lu".split("l"))
print("hello world ke ru lu".split("l",1))
输出:
['hello', 'world', 'ke', 'ru', 'lu']
['he', '', 'o wor', 'd ke ru ', 'u']
['he', 'lo world ke ru lu']
11.3、从右开始切分字符串
方法
rsplit()
说明
从右开始切分字符串,可以指定切分次数和对象 ,默认以空格切割
案例
print("hello world ke ru lu".rsplit())
print("hello world ke ru lu".rsplit("l"))
print("hello world ke ru lu".rsplit("l",1))
输出:
['hello', 'world', 'ke', 'ru', 'lu']
['he', '', 'o wor', 'd ke ru ', 'u']
['hello world ke ru ', 'u']</code></pre>
<p>12、字符串的拼接</p>
<pre><code>12.1、join
将指定的字符串插入到后面的序列的每两个元素之间,进行拼接,形成一个新的字符串。
print("*".join("hello world"))
print(" ".join("hello world"))
print("".join("hello world"))
print(" % ".join("hello world"))
输出:
h*e*l*l*o* *w*o*r*l*d
h e l l o w o r l d
hello world
h % e % l % l % o % % w % o % r % l % d
12.2、+
将两个字符串拼接起来。
print("ke"+"ru")
输出:
keru
12.3、*
将指定的字符串进行重复。
print("ke"*3)
输出:
kekeke</code></pre>
<p>13、字符串的编码</p>
<pre><code>encode /加码
decode /解码
首先以gbk进行解码。解码后得到Unicode的中国,unicode是python2的核心编码。
print("中国".decode("gbk"))
#===================================================================
对解码后的内容进行加码
print("中国".decode("gbk").encode("utf-8")) #由gbk转码为utf-8的过程。
输出:
中国
中国
中国</code></pre>
<p>14、格式化字符串</p>
<pre><code>14.1、使用 % 操作符
“%s” 可以接收数字和字符,字符类型的格式化。
print("Tom is %s years old"%"18")
print("%s is %s years old"%("Tom",18))
结果:
Tom is 18 years old
Tom is 18 years old
“%d” 只能接收数字 ,整数的格式化。
print("%s is %d years old"%("Tom",18))
print("%s is %d years old" %("Tom","18"))
结果:
Tom is 18 years old
TypeError: %d format: a number is required, not str
“%2d” 至少保留两位长度,不足默认一以空白从左补充。
print("%s is %2d years old"%("TOM",0.068787878))
print("%s is %0.2d years old"%("TOM",0.068787878))
结果:
TOM is 0 years old
TOM is 00 years old
“%f” 保留六位小数。
“%0.1f” 保留一位小数。
“%0.2f” 保留两位小数 ,浮点的格式化。
print("%s is %f years old"%("TOM",0.068787878))
print("%s is %0.1f years old"%("TOM",0.068787878))
print("%s is %0.2f years old"%("TOM",0.068787878))
结果:
TOM is 0.068788 years old
TOM is 0.1 years old
TOM is 0.07 years old
“%(key)s” 映射式格式符。
print("%(name)s is %(num)s years old,%(name)s have %(num)s $RMB"%({"name":"TOM","num":18}))
结果:
TOM is 18 years old,TOM have 18 $RMB
print("{} is {} years old".format("TOM",18))
结果:
TOM is 18 years old
%c
单个字符。
%d或%i
十进制整数。
%x
十六进制整数。
%f或%F
浮点数。
%r
字符串(采用repr()显示)。
%o
八进制整数。
%e
指数(基数写为e)。
%E
指数(基数写为E)。
%%
字符%。
案例
template = '编号:%09d\t 公司名称:%s \t官网: http://www.%s.com' #定义模板。
x1 = (6,'百度','baidu') #定义转换的内容
x2 = (8,'华为','huawei') #定义转换的内容
print(template%x1) #格式化输出
print(template%x2) #格式化输出
编号:000000006 公司名称:百度 官网: http://www.baidu.com
编号:000000008 公司名称:华为 官网: http://www.huawei.com
14.2、format()方法
(1)格式
str.format(args)
(2)常用格式化字符
s
对字符串类型格式化。
d
十进制数。
c
将十进制数自动转换为对应的Unicode字符。
e或E
转换为科学计数法表示在格式化。
g或G
自动在e和f或E和F中切换。
b
将十进制数转换成二进制数表示再格式化。
o
将十进制数转换成八进制数再格式化。
x或X
将十进制数转换成十六进制数再格式化。
f或F
转化为浮点数(默认小数点后保留6位)再格式化。
%
显示百分比(默认显示小数点后6位)。
(3)案例
template = '编号:{:0>9s}\t 公司名称:{:s} \t官网: http://www.{:s}.com' #定义模板。
x1 = template.format('6','百度','baidu') #定义转换的内容
x1 = template.format('8','华为','huawei') #定义转换的内容
print(x1) #格式化输出
print(x2) #格式化输出</code></pre>