python字符串

时间:2024-03-17 10:38:12

一、字符串定义

  1.可用" "、''、""" """定义

  2.转译特殊字符 "\"

python字符串

二、字符串操作

  s = 'welcomewestos'   ##从0开始,到length-1结束

 1.索引

  print(s[4])    ##打印4索引,即第5个字符

 2.切片

  print(s[1:3])   ##从0索引开始,到3索引结束

  print(s[:])     ##打印字符串

  print(s[1:5:2])  ##从1索引开始,到5索引结束,步长为2

  print(s[-4:])  ##打印最后4个字符

  print(s[-2])   ##打印倒数第2个字符

  print(s[::-1])  ##反转字符串

python字符串

 3.连接

print("hello "  +  "word")

print("hello " +  s)

 4.重复

print("*"*10  +  "student"  +  "*"*10)

python字符串

 5.成员操作符

print("com"in s)   ##字符串s是否含有com

print("test"in s)

6.计算长度  len(s)

python字符串

练习:

 1.遍历打印字符串s,要求以tab键隔开

python字符串

 2.判断回文数

python字符串

三、循环语句

 1.for-else   ###实现登陆效果,三次不对报错!

python字符串

 2.while-else  ###实现登陆效果,三次不对报错!

python字符串

四、字符串处理

 1.字符串的搜索与替换

s = "hello everyone,welcome to westos"

print(s.find("e"))    ##从start开始查找e,打印匹配的索引值

print(s.rfind('e'))   ##从end开始查找e,打印匹配的索引值

print(len(s)) 

print(s.replace('s','E'))  ##将s替换成E

python字符串

 2.删除空格

s = "   hello   "

print(s.strip())    ##删除所有空格,包括\n,\t

print(s.lstrip())   ##删除左边空格

print(s.rstrip())  ##删除右边空格

print(s.replace(' ',''))

python字符串

 3.字符串对齐

s = "student system"

print(s.center(20))   ##字符串行长度20,s放中间

print(s.center(20,'*'))  ##字符串行长度20,s放中间,其他用*补全

print(s.ljust(20,'*'))   ##字符串行长度20,s放左边,其他用*补全

print(s.rjust(20,'*'))   ##字符串行长度20,s放右边,其他用*补全

python字符串

 4.字符统计

s = 'hello everyone,are you tired?'

print(s)

print(s.count('e'))    ##统计e出现的次数

print(s.count('re'))   ##统计re出现的次数

print(s.count('lo'))  ##统计lo出现的次数

python字符串

 5.字符开头

str1 = 'http://test'

str2 = 'https://test'

str3 = 'ftp://test'

str4 = 'file://test'

print(str1.startswith(('https://','http://')))   ##或

print(str1.startswith('https://'))   ##判断str1的开头

python字符串

 6.字符结尾

str1 = 'hello.jpg'

str2 = 'hello.img'

str3 = 'hello.png'

print(str1.endswith('.png'))   ##判断str1的结尾

print(str1.endswith(('.png','.jpg')))   ##或

python字符串

 7.字符串的连接与分离

ip = '172.25.33.321'

print(ip.split(' . '))    ##以'.'为分隔符,分离ip

print(ip.split(' . ')[::-1])   ##将分离结果倒序打印

python字符串

info = '23+45+12'

print(eval(info))   ##求和

new_info=info.replace('+','*')   ##替换字符

print(eval(new_info))   ##求积

python字符串

 8.判断字符串索引的类型

  s.isalnum()   ##判断是否都是字母或数字

  s.isalpha()    ##判断是否都是字母

  s[4].isdigit()  ##判断索引4是否为数字

  s.islower()    ##判断是否都是小写

  s[10].isspace()  ##判断索引10是否为英文空格

  s.istitle()   ##判断是不是都是标题(有大小写)

  s.isupper()   ##判断是不是都为大写字母

python字符串

练习:

   1.判断ip是否合法

python字符串

   2.打印/var/log目录下以.log结尾的文件

python字符串

 8.最大值、最小值

print(max('hello'))   ##比较ASCII码

print(min('hello'))

print(ord('t'))   ##打印t的ASCII码值

python字符串

python3:没有cmp函数,比较大小;但是python2有

 9.枚举

python字符串

 10.zip

s1 = 'hello'    ##一一对应,多的不做处理

s2 = 'westos'

python字符串

 11.join

python字符串

五、练习

 1.求给定字符串中数字、字母、空格和其他字符的个数:

python字符串

 2.求给定字符的最大公约数和最小公倍数:

python字符串