这篇教程Python 字符串的有关知识详解写得很实用,希望能帮到您。
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[n] 指定下标读取序列中某个元素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 91letters2 = ""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()方法未找到子字符串时会返回 -1str2 = "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
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注51zixue.net的更多内容! 推荐一款高效的python数据框处理工具Sidetable Django |