python字符串

一、字符串定义

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

  2.转译特殊字符 "\"

二、字符串操作

  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])  ##反转字符串

 3.连接

print("hello "  +  "word")

print("hello " +  s)

 4.重复

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

 5.成员操作符

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

print("test"in s)

6.计算长度  len(s)

练习:

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

 2.判断回文数

三、循环语句

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

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

四、字符串处理

 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

 2.删除空格

s = "   hello   "

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

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

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

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

 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放右边,其他用*补全

 4.字符统计

s = 'hello everyone,are you tired?'

print(s)

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

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

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

 5.字符开头

str1 = 'http://test'

str2 = 'https://test'

str3 = 'ftp://test'

str4 = 'file://test'

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

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

 6.字符结尾

str1 = 'hello.jpg'

str2 = 'hello.img'

str3 = 'hello.png'

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

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

 7.字符串的连接与分离

ip = '172.25.33.321'

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

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

info = '23+45+12'

print(eval(info))   ##求和

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

print(eval(new_info))   ##求积

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

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

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

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

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

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

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

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

练习:

   1.判断ip是否合法

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

 8.最大值、最小值

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

print(min('hello'))

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

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

 9.枚举

 10.zip

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

s2 = 'westos'

 11.join

五、练习

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

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

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值