字符串
input获取的内容都存储为字符串
字符串拼接:a+b
#encoding:utf-8
name = "xijuanxia"
print(name[3])
print(name[-1]) #取最后一个字母
print(name[len(name)-1]) #取最后一个字母
结果:
u
a
a
name[9] :越界会导致程序奔溃
切片:
name = "xijuanxia"
print(name[2:5]) #2-4
print(name[2:-2]) #从2到倒数第三个
print(name[2:]) #从2到结束
print(name[2:-1:2]) #起始位置:终止位置:步长
print(name[-1:0:-1]) #逆序,缺首字母
print(name[-1::-1]) #逆序
结果:jua
juanx
juanxia
jax
aixnauji
aixnaujix
字符串的常见操作
find() 用来查找字符串的位置
mystr = "hello world itcast and"
mystr.find("and")
mystr.find("xjx")
结果:9
-1
find() 从左边开始找
rfind() 从右边开始找
如果有两个则返回第一个的位置
count() 查找字符串出现的个数
mystr = "hello world itcast and"
mystr.count("or")
结果:1
replace()
mystr = "hello world itcast and"
mystr.replace("world","xijuanxia")
'hello xijuanxia itcast and'
mystr
'hello world itcast and'
替换完后mystr的值不变,且被替换项若有多个,则会全部替换。若只想替换一个 mystr.replace("world","xijuanxia",1)第三个参数写出替换第几个
split()
mystr.split(" ") #按空格切割,切割完就不再有空格
['hello', 'world', 'itcast', 'and']
capitalize()
首字母大写
titile()
把每个单词的第一个字母都大写
startswith()
以什么开头
endswith()
以什么结束
file_name = "xjx.txt"
file_name.endswith(".txt")
True
lower()
把所有字母转换为小写
upper()
把所有字母转换为大写
ljust()
放到左边
rjust()
放到右边
center()
xjx.center(50)
放到中间,占宽度50
partition
以某个字符串为分割点,分成三部分,默认从左边开始分割
xjx = "hello xjx is a good student"
xjx.partition("is")
('hello xjx ', 'is', ' a good student')
rpartition
从右边开始分割,以某个字符串为分割点,分成三部分
splitlines()
xjx = "hello xjx is a good student"
xjx.splitlines()
['hello xjx is a good student']
isalpha()
判断是不是纯字母
isdigit()
判断是不是纯数字
isalnum()
判断是不是字母或数字
isspace()
是不是包含空格
join()
以“=”把a里的元素连接起来
a = ["aaa","bbb","ccc"]
b = "="
b.join(a)
'aaa=bbb=ccc'