目录
1.什么是字符串
字符串由很多有效字符,如数字、字母、下划线组成的一串字符
2.定义方法
1.由双引号,单引号,三双引号,三单引号定义
2.s = str()
3.常见的方法
(通过调用help文档查看)
>>> s = "hahahaha"
>>> s 'hahahaha'
>>> s.capitalize()
'Hahahaha'
2.center(width, fillchar=' ') ---- 字符串长度居中
>>> s = "hahahaha"
>>> s.center(30)
' hahahaha '
>>> s.center(30,"*")
'***********hahahaha***********'
3.count() ---- 统计字符或者字符串出现的次数
>>> s = "hahahaha"
>>> s 'hahahaha'
>>> s.count("h")
4
>>> s.count("ha")
4
>>> s.count("haha")
2
4.endswith() ---- 判断字符串是不是以XXX结尾
5.startswith() ---- 判断字符串是不是以XXX开头
6.index() ---- 查询字符或者字符串在字符串中出现的第一次的位置,如果没有则抛出异常
>>> s = "hahahaha"
>>> s.encode()
b'hahahaha'
>>> d = s.encode()
>>> d
b'hahahaha'
>>> type(d)
<class 'bytes'>
>>> d.decode()
'hahahaha'
>>> ss = d.decode()
>>> type(ss)
<class 'str'>
11.format() ----- 格式化字符串 a = 3 b =2 print("a = {} ,b ={}".format(a,b))
12.islower() ------ 判断字母是否全为小写
>>> s = "hahahaha"
>>> s
'hahahaha'
>>> s.islower()
True
>>> s.isupper()
False
14.istitle() ---- 判断是否为标题
>>> ss = "This is ..."
>>> ss.istitle()
False
>>> ss = "This Is .."
>>> ss.istitle()
True
15.isspace() --- 判断是否为空格位
16.isdigit() ---- 判断是否为数字
>>> s = "hahahaha"
>>> s
'hahahaha'
>>> s.isdigit()
False
>>> ss = "1234"
>>> ss.isdigit()
True
17.isalnum() ----- 不是判断是否位数字,判断是否为有效字符(数字、字母、下划线)
>>> s = "hahahaha"
>>> ss = "$$$$$"
>>> ss.isalnum()
False
>>> s
'hahahaha'
>>> s.isalnum()
True
18.isalpha() ---- 是否全为字母
>>> s = "hahahaha"
>>> s.isalpha()
True
19.title() ----- 将字符串转换为标题
>>> ss = "this is a dog"
>>> ss.title()
'This Is A Dog'
20.lower() ----- 将字符全部转换为小写
s = "hahahaha"
>>> s
'hahahaha'
>>> s.upper()
'HAHAHAHA'
22.split() ---- 将字符串按照特定的格式进行分割,返回值是一个列表
>>> s = "hahahaha"
>>> ss = "this is a dog"
>>> ss
'this is a dog'
>>> ss.split(" ")
['this', 'is', 'a', 'dog']
>>> ss
'this is a dog'
>>> ss.split("s")
['thi', ' i', ' a dog']
23.join() --- 按照特定的符号将一个可迭代对象拼接字符串(注意的是这个方法不是列表或者其他容器的方法)
>>> ls = ["a","b","c"]
>>> " ".join(ls)
'a b c'
>>> "*".join(ls)
'a*b*c'
24.strip() ----- 清除字符串两侧空格
>>> ss = " name "
>>> ss.strip()
'name'
27.replace(old,new) ----- 用新的字符替换旧的字符
>>> s = "hahahaha"
>>> s.replace("h","H")
'HaHaHaHa'
28.ljust() ------- 左对齐
>>> s = "hahahaha"
>>> s.ljust(30)
'hahahaha '
>>> s.rjust(30)
' hahahaha'
>>> s.rjust(30,"*")
'**********************hahahaha'