python—字符串

一、字符串定义

1.可用” “、”、”“” “”“定义

2.转译特殊字符 “\”

>>>s1 = "this's a python"
>>>s2 = '"hello"'
>>>s3 = """"hello" this's a python"""
>>>s4 = 'this\'s a python'
>>>s1
"this's a python"
>>>s2
'"hello"'
>>>s3
'"hello" this\'s a python'
>>>s4
"this's a 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]) ##反转字符串
这里写图片描述

3.连接

print(“hello ” + “word”)

print(“hello ” + s)
这里写图片描述

4.重复

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

5.成员操作符

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

print("test"in s)

6.计算长度 len(s)

这里写图片描述

7.for循环

1.遍历打印字符串s,要求以tab键隔开
这里写图片描述
练习
判断回文数
这里写图片描述

三、循环语句

1、for-else循环

登陆系统,允许三次尝试登陆

for count in range(3):
    user = input("用户名:")
    passwd = input("密码:")
    count +=1
    if user == "root" and passwd == "redhat":
        print("登陆成功!!")
        break
    else:
        print("用户名或密码错误!")
else:
    print("Erroe:超过三次登陆机会")

这里写图片描述

2.while-else

实现登陆效果,三次不对报错!

count = 0
while count < 3:
    user = input("用户名:")
    passwd = input("密码:")
    count +=1
    if user == "root" and passwd == "redhat":
        print("登陆成功!!")
        break
    else:
        print("用户名或密码错误!")
else:
    print("Erroe:超过三次登陆机会")

四、字符串处理

1.字符串的搜索与替换

s = "hello my friend,welcome to my home!"
print(s.find("o"))
print(s.rfind(("")))
print(len(s))
print(s.replace('o','a'))

这里写图片描述

2.删除空格

s = "   python   "

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

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

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

print(s.replace(' ','*'))   空格用*替换

这里写图片描述

3.字符串对齐

s = "hello world"

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.2'

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

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

这里写图片描述

8、求和和求积

info = '24+45+12'
print(eval(info))    求和
new_info = info.replace('+',"*")   替换字符
print(eval(new_info))   求积

这里写图片描述

9、判断字符串索引的类型

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

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

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

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

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

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

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

这里写图片描述
练习
1、判断ip是否合法:

ip = input('IP:')
if len(ip.split('.')) == 4:
    for num in ip.split('.'):
        num = int(num)
        if not 0 < num <= 255:
            print(ip+ '不合法')
            break
    else:
        print(ip + '合法')
else:
    print(ip + '不合法')

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

import os
for filename in os.listdir('/var/log'):
    if filename.endswith('.log'):
        print(filename)

这里写图片描述

10、最大值、最小值

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

print(min('hello'))

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

这里写图片描述

11、枚举

这里写图片描述

12.zip

s1 = 'hello'
s2 = 'westos'
for i in zip(s1,s2):
    print(i)

这里写图片描述

13.join(连接)

这里写图片描述
练习
1.求给定字符串中数字、字母、空格和其他字符的个数:

 str = input("请输入字符串:")
count1 = count2 = count3 = count4 = 0
for N in range(1,len(str)):
    if str[N].isspace():
        count1 += 1
    elif str[N].isdigit():
        count2 += 1
    elif str[N].isalpha():
        count3 += 1
    else:
        count4 += 1
print("这串字符中的空格有%s个,数字有%s个,字母有%s个,其他字符%s个" %(count1,count2,count3,count4))

这里写图片描述
2.求给定字符的最大公约数和最小公倍数:

num1 = int(input("第一个数字:"))
num2 = int(input("第二个数字:"))
min_num = min(num1,num2)
for i in range(min_num,0,-1):
    if num1%i == 0 and num2%i == 0:
        max_res =i
        break
min_res = int(num1*num2)// max_res
print("%s%s的最大公约数是%s,最小公倍数是%s" %(num1,num2,max_res,min_res))

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41789003/article/details/80511959