您的位置:首页 > 编程语言 > Python开发

Python 字符串的有关知识详解

2021-11-27 04:06 836 查看
目录

1.部分转义字符

转义字符
# \\ 反斜线
str1 = "qqq\\qq"
print(str1)
# 输出 qqq/qq
# \b 退格键(Backspace)
str2 = "qqq\b"
print(str2)
# 输出 qq
# \' 单引号 \"双引号
str3 = "qq\'qqqqq\""
print(str3)
# 输出 qq'qqqqq"
# \n 换行
str4 = "qqqq\nqq"
print(str4)
# 输出 qqqq
#     qq
# \t 制表符(Tab)
str5 = "a\taa"
print(str5)
# 输出 a   aa

2.slice 切片读取字符串

s = "hello world sssss sssss sssss"
# s
 指定下标读取序列中某个元素
print(s[1])
# e
# s[n: m] 从下标值n读取到m-1,若干个元素
print(s[0: 4])
# hell
# s[n:] 从下标值n读取到最后一个元素
print(s[3:])
# lo world
# s[:m] 从下标值0读取到m-1个元素
print(s[:5])
# hello
# s[:] 表示会复制一份序列的元素
print(s[:])
# hello world
# s[::-1] 将整个序列元素反转
print(s[::-1])
# dlrow olleh

3.调用split()方法分割字符串 ASCII字母

# 字符串.split(分隔符,分隔次数)
# 输出26个小写字母并反转输出
letters = ""
for x in range(97, 123):
letters += str(chr(x))
print(letters)
print(" ")
print(letters[::-1])
# ord()返回字符所对应的ASCII码
# chr()返回ASCII码对应的字符
# 输出26个大写字母并反转输出 A 65 Z 91
letters2 = ""
for n in range(65, 91):
letters2 += chr(n) + " "
print(letters2)
print(letters2[::-1].split(" ",5))  # 字符串.split(分隔符,分隔次数)

4.与字母大小写有关方法

str = "My name in Zyj hello world"
# capitalize() 只有第一个单词首字母大写,其余都小写
print(str.capitalize())
# My name in zyj hello world
# lower() 将字母转换为小写
print(str.lower())
# my name in zyj hello world
# upper() 将字母转换为大写
print(str.upper())
# MY NAME IN ZYJ HELLO WORLD
# title() 每个单词首字母大写,其余都小写
print(str.title())
# My Name In Zyj Hello World
# islower() isupper() istitle() 判断字符串是否符合格式
print(str.isupper())
# False

5.搜索查找字符串

str1 = "Myaa namess inddaa Zyjcc helloxx worldbb"
# 1.count.py 搜索特定字符串存在的个数
print(str1.count("aa"))
# 2.查找字符串  str.find(字符或字符串 ,开始下标,结束下标) 返回第一次找到该字符串时的下标编号
# find()方法未找到子字符串时会返回 -1
str2 = "My name in Zyj hello world My name in Zyj hello world"
print(str2.find("in", ))  # 寻找子字符串in,从下标编号0开始
print(str2.find("in", 9))  # 寻找子字符串in,从下标编号9开始
# 3. str.index(字符或字符串 ,开始下标,结束下标) 返回指定字符串下标值
print(str2.index("name"))
# index 与 find 差别,index()查找不到会报错,find()会返回 -1 值
# 4.startswith(字符或字符串 ,开始下标,结束下标) 判断字符串开头字符是否含有子字符
str3 = "My name in Zyj hello world My name in Zyj hello world"
print(str3.startswith("name", 3))  # True
# 5.str.endswith(字符或字符串 ,开始下标,结束下标) 判断字符串结尾字符是否含有子字符
print(str3.endswith("world"))  # True

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 字符串 详解