python——字符串的处理(索引,切片,重复,连接,成员操作符,迭代....)

早过忘川 提交于 2019-12-18 11:24:51

1.字符串的定义

a = 'hello'
b = 'what\'s up'
c = "what's up"
d = """     ##定义多个字符串
    用户管理系统
    -查询
    -添加
    -删除
"""
print(a)
print(b)
print(c)
print(d)

输出结果:
hello
what's up
what's up

    用户管理系统
    -查询
    -添加
    -删除

2.字符串的常用转义字符:

\n 换行
\t 一个tab键

3.字符串的特性:索引,切片,重复,连接,成员操作符,迭代

[0] 第一个字符
[-1]或[最后一个数字] 表示最后一个字符
[0:3] 第012个字符
[:3] 显示前三个字符012
[2:] 前两个不显示(显示除了前二个字符之外的其他字符都显示)
[0:4:2] 第0 2个字符从第0个到第4个字符,步长为2
[:] 所有字符
[::-1] 将字符反转
[s * 3] 所有字符重复三次

索引

s = 'hello'
print(s[0])
print(s[1])
print(s[-1])

输出结果:
h
e
o

切片

s = 'hello'
print(s[0:3]) # 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
print(s[0:4:2])
#显示所有字符
print(s[:])
#显示前3个字符
print(s[:3])
#对字符串倒叙输出
print(s[::-1])
#除了第一个字符以外,其他全部显示
print(s[1:])

输出结果:
hel
hl
hello
hel
olleh
ello

重复

s = 'hello'
print(s * 5)
输出结果:
hellohellohellohellohello

连接

s = 'hello'
print(s + 'world')
输出结果:
helloworld

成员操作符

s = 'hello'
print('h' in s)
输出结果:
True

for循环(迭代循环遍历)

s = 'hello'
for i in s:
    print(i)
输出结果:
h
e
l
l
o

4.字符串匹配开头和结尾
匹配开头:

url3 = 'http://172.25.254.250/index.html'

if url3.startswith('https://'):
    print('获取网页')
else:
    print('未找到网页')

输出结果:
未找到网页

匹配结尾:

filename = 'hello.loggg'

if filename.endswith('.log'):
   print(filename)
else:
   print('error filename')

输出结果:
error filename

5.字符串对齐

.center( , ) 居中
.ljust( , ) 左对齐
.rjust( , ) 对齐
print('学生管理系统'.center(30))		##居中
print('学生管理系统'.center(30,'@'))	##居中,并且两边用@填充
print('学生管理系统'.ljust(30,'#'))	##左对齐,用#填充
print('学生管理系统'.rjust(30,'#'))	##右对齐,用#填充

6.字符串判断大小写和数字
判断字符串里每个元素为什么类型
一旦有一个元素不满足,就返回False

print('123'.isdigit())
print('123abc'.isdigit())
输出结果:
True
False

title:判断某个字符串是否为标题(第一个字母大写,其余字母小写)

print('Hello'.istitle())
print('HeLlo'.istitle())
输出结果:
True
False

转换成大写,并判断是否大写

print('hello'.upper())
print('hello'.isupper())
输出结果:
HELLO
False

转换成小写,并判断是否为小写

print('HELLO'.lower())
print('HELLO'.islower())
输出结果:
hello
False

判断是否为字母数字

print('hello123'.isalnum())   ##字母和数字(alnum)
print('123'.isalpha())        ##字母(alpha)
print('aaa'.isalpha())
输出结果:
True
False
True

7.字符串的搜索、替换、统计

find 搜索
replace 替换
count 统计
len 统计长度
s = 'hello world hello'
#find找到子串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
#rfind找到子串,并返回最大索引
print(s.rfind('hello'))

#替换字符串中所有的'hello'为'westos'
print(s.replace('hello','westos'))

print('hello'.count('l'))
print('hello'.count('ll'))

print(len('hello'))

输出结果如下:
0
6
12
westos world westos
2
1
5

字符串的连接和分离

split 分离
join 拼接
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!