• [Python] 字符串操作及方法总结


    1.创建字符串

    字符串是Python中最常用的数据类型(字符串是字符的序列)

    我们可以使用引号( ' 或 " )来创建字符串

    1. txt1 = 'Hello World!!'
    2. print(txt1) # Hello World!!
    3. txt2 = "Hello World!!"
    4. print(txt2) # Hello World!!
    1. str1 = 'What\'s your name?'
    2. str2 = "What's your name?"
    3. print(str1) # What's your name?
    4. print(str2) # What's your name?

    补充:字符串合并可使用+运算符 

    1. str1 = 'Hello'
    2. str2 = 'World'
    3. print(str1 + str2) # HelloWorld
    4. print(str1 + ' ' + str2) # Hello World

    2.字符串常见操作方法

    2.1索引

    字符串中的所有元素都是有编号的,即我们所说的索引值,从0开始递增

    我们可以使用索引来获取字符

    1. txt = 'ABCDEFGHIJKLMN'
    2. print(txt[0]) # A
    3. print(txt[2]) # C
    4. print(txt[-2]) # M
    5. print(txt[-1]) # N

    2.2切片

    除了使用索引访问单个字符外,我们还可以使用切片(slicing)来访问特定范围内的字符

    1. tag = 'Hudas Blog'
    2. tag[9:36] # 'https://blog.csdn.net/Hudas'
    3. tag[38:-4] # 'Hudas Blog'

    扩展补充知识

    Python切片操作https://blog.csdn.net/Hudas/article/details/125905111

    2.3获取字符串的长度

    len(str)可用于获取字符串长度

    注明:str代表字符串

    1. txt = 'I love Python very much!!'
    2. print(len(txt)) # 25

    2.4检查字符串是否以"xxxx"开头 

    1. exp_str = "Hello World!!"
    2. result = exp_str.startswith("Hello")
    3. print(result) # True

    2.5检查字符串是否以"xxxx"结尾

    1. txt = "China is a great country"
    2. result = txt.endswith("country")
    3. # True
    4. print(result)

    2.6字符串大小写转换

    upper()用于返回字符串的大写版本

    lower()用于返回字符串的小写版本

    capitalize()title()用于将字符串转换为词首大写(首字母大写)

    1. txt = "hello world!!"
    2. # 把所有字符中的小写字母转换成大写字母
    3. print(txt.upper()) # HELLO WORLD!!
    4. # 把所有字符中的大写字母转换成小写字母
    5. print(txt.lower()) # hello world!!
    6. # 把第一个字母转化为大写字母,其余小写
    7. print(txt.capitalize()) # Hello world!!
    8. # 把每个单词的第一个字母转化为大写,其余小写
    9. print(txt.title()) # Hello World!!
    10. txt1 = "blog.csdn.net"
    11. # BLOG.CSDN.NET
    12. print(txt1.upper())
    13. # blog.csdn.net
    14. print(txt1.lower())
    15. # Blog.csdn.net
    16. print(txt1.capitalize())
    17. # Blog.Csdn.Net
    18. print(txt1.title())

    2.7检测字符串中是否包含子字符串

    index()方法与find()方法功能一样,用于查询指定检索的字符串是否包含在目标字符串内,如果包含在内,返回第一个指定检索字符串在目标字符串起始索引值

    如果指定检索的字符串不在目标字符串内,index()方法会报异常,find()方法返回-1

    1. str1 = 'Python'
    2. str1.find('t') # 2
    3. str1.index('t') # 2
    4. str1.find('hon') # 3
    5. str1.index('hon') # 3
    6. str1.find('z') # -1
    7. str1.index('z') # ValueError: substring not found

    扩展补充知识

    index()方法 VS find()方法https://blog.csdn.net/Hudas/article/details/122873780

    2.8字符串替换

    replace()可以将指定子字符串替换为另一个字符串,并返回替换后的结果

    1. txt = 'This is a test'
    2. # This is a demo
    3. print(txt.replace('test','demo'))

    替换字符串中的多个子字符

    1. sentence = "The lazy brown fox jumps over the lazy dog"
    2. for words in (("brown", "red"), ("lazy", "quick")):
    3. sentence = sentence.replace(*words)
    4. # The quick red fox jumps over the quick dog
    5. print(sentence)

    2.9去除字符串中的space字符 

    strip()可以将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果

    lstrip()去除字符串左边空格

    rstrip()去除字符串右边空格 

    1. txt = " Andy437 "
    2. # 去除首尾空格
    3. print(txt.strip()) #Andy437
    4. # 去除左边空格
    5. print(txt.lstrip()) #Andy437
    6. # 去除右边空格
    7. print(txt.rstrip()) # Andy437

    补充扩展知识

    strip()方法https://blog.csdn.net/Hudas/article/details/122849506

    2.10字符串拆分为序列 

    split()用于将字符串拆分为序列

    注意:如果没有指定分隔符,将默认在单个或多个连续的空白符(空格、制表符、换行符等)处进行拆分 

    1. txt = '1+2+3+4+5'
    2. # ['1', '2', '3', '4', '5']
    3. print(txt.split('+'))
    4. txt1 = '/usr/bin/env'
    5. # ['', 'usr', 'bin', 'env']
    6. print(txt1.split('/'))
    7. txt2 = 'Using the default'
    8. # ['Using', 'the', 'default']
    9. print(txt2.split())

    补充扩展知识

    split()方法https://blog.csdn.net/Hudas/article/details/122849811

    2.11合并序列

    join()用于合并序列的元素,其作用与split相反

    注意:所合并序列的元素必须都是字符串

    1. nums = [1, 2, 3, 4, 5]
    2. s = '+'
    3. # 报错,TypeError: sequence item 0: expected str instance, int found
    4. print(s.join(nums))
    1. nums = ['1', '2', '3', '4', '5']
    2. s = '+'
    3. # '1+2+3+4+5'
    4. print(s.join(nums))

    扩展补充知识

    join()方法https://blog.csdn.net/Hudas/article/details/122850092

    2.12计算字符串中某字符出现次数

    count()用于统计字符串里某个字符或子字符串出现的次数

    1. # 检查字符'a'在sentence中出现的次数
    2. sentence = 'Canada is located in the northern part of North America'
    3. counter = sentence.count('a')
    4. print(counter) # 6

    我们也可以使用一下方法实现上述count()的效果

    1. # 检查字符'a'在sentence中出现的次数
    2. sentence = 'Canada is located in the northern part of North America'
    3. # 方法1
    4. import re
    5. counter = len(re.findall("a", sentence))
    6. print(counter) # 6
    7. # 方法2
    8. from collections import Counter
    9. counter = Counter(sentence)
    10. print(counter['a']) # 6

    扩展补充知识

    count()方法https://blog.csdn.net/Hudas/article/details/122941544

    2.13格式化字符串

    格式化字符串函数str.format()

    1. # 下面输出结果都为"My name is Andy, I'am 18"
    2. txt1 = "My name is {fname}, I'am {age}".format(fname = "Andy", age = 18)
    3. txt2 = "My name is {0}, I'am {1}".format("Andy",18)
    4. txt3 = "My name is {}, I'am {}".format("Andy",18)

    扩展补充知识

    format格式化函数https://blog.csdn.net/Hudas/article/details/122849967

    2.14检测字符串是否由字母/数字组成

    isalpha()用于检测字符串是否只由字母组成,如果字符串中所有字符都是字母则返回True,否则返回False

    1. txt1 = "python"
    2. print(txt1.isalpha()) #True
    3. # 中文的汉字会被isalpha判定为True
    4. txt2 = "这是一个例子"
    5. print(txt2.isalpha()) # True
    6. # 如果想区分中文和英文,可以使用如下方法
    7. print(txt2.encode("utf-8").isalpha()) # False
    8. txt3 = "Andy安迪"
    9. print(txt3.isalpha()) # True
    10. print(txt3.encode("utf-8").isalpha()) # False

    isdigit()用于检测字符串是否只由数字组成,结果返回True或False

    注意:只对0和正数有效

    1. str1 = '123456'
    2. print(str1.isdigit()) # True
    3. str2 = "Hello Wrold!!"
    4. print(str2.isdigit()) # False
    5. str3 = '0'
    6. print(str3.isdigit()) # True
    7. str4 = '-1'
    8. print(str4.isdigit()) # False
    9. str5 = '1.437'
    10. print(str5.isdigit()) # False
    11. str6 = '12.0'
    12. print(str6.isdigit()) # False

    isalnum()用于检测字符串是否由字母和数字组成,结果返回True或False

    1. str1 = "year2022"
    2. print(str1.isalnum()) # True
    3. str2 = "HelloWorld"
    4. print(str2.isalnum()) # True
    5. str3 = "Hello World"
    6. print(str3.isalnum()) # False
    7. str4 = "437"
    8. print(str4.isalnum()) # True

    2.15检测字符串是否由小写/大写字母组成

    islower()用于检测字符串中所有的字母是否都为小写,结果返回True或False

    1. txt1 = "HELLO world!!!"
    2. print(txt1.islower()) # False
    3. txt2 = "hello world!!!"
    4. print(txt2.islower()) # True
    5. txt3 = '437'
    6. print(txt3.islower()) # False
    7. txt4 = 'andy437'
    8. print(txt4.islower()) # True
    9. txt5 = 'Andy437'
    10. print(txt5.islower()) # False

    isupper()用于检测字符串中所有的字母是否都为大写,结果返回True或False

    1. txt1 = "HELLO WORLD!!!"
    2. print(txt1.isupper()) # True
    3. txt2 = "HELLO world!!!"
    4. print(txt2.isupper()) # False
    5. txt3 = '437'
    6. print(txt3.isupper()) # False
    7. txt4 = 'andy437'
    8. print(txt4.isupper()) # False
    9. txt5 = 'Andy437'
    10. print(txt5.isupper()) # False
    11. txt6 = 'ANDY437'
    12. print(txt6.isupper()) # True

    istitle()用于检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写,结果返回True或False

    1. txt = 'Andy'
    2. print(txt.istitle()) # True
    3. txt1 = 'Aa Bc'
    4. print(txt1.istitle()) # True
    5. txt2 = 'Aa_Bc'
    6. print(txt2.istitle()) # True
    7. txt3 = 'Aa bc'
    8. print(txt3.istitle()) # False
    9. txt4 = 'Aa_bc'
    10. print(txt4.istitle()) # False
    11. txt5 = 'Aa BC'
    12. print(txt5.istitle()) # False
    13. txt6 = '437'
    14. print(txt6.istitle()) # False
    15. txt7 = 'A437'
    16. print(txt7.istitle()) # True
    17. txt8 = 'helloWorld'
    18. print(txt8.istitle()) # False

    2.16检查字符串是否为空 

    isspace()用于检测字符串是否只由空格组成,结果返回True或False

    1. txt1 = " "
    2. print(txt1.isspace()) # True
    3. txt2 = "Test"
    4. print(txt2.isspace()) # False
    5. txt3 = " Test "
    6. print(txt3.isspace()) # False
    7. txt4 = ' \t'
    8. print(txt4.isspace()) # True
    9. txt5 = '\n'
    10. print(txt5.isspace()) # True
    11. txt6 = 'Aa Bb'
    12. print(txt6.isspace()) # False

    注意

    1. txt = ''
    2. print(txt.isspace()) # False

    扩展补充判断字符串是否为空的其他方法

    1. username1 = ""
    2. # 方法1:使用字符串长度判断
    3. if len(username1) == 0:
    4. print("用户名不能为空")
    5. # 方法2:使用==判断是否为空
    6. if username1 == '':
    7. print("用户名不能为空")
    8. # 方法3:直接判断是否为空
    9. if username1:
    10. print("Welcome!!")
    11. else:
    12. print("用户名不能为空")
    13. username2 = " "
    14. # 使用.isspace()判断是否字符串全部是空格
    15. if username2.isspace() == True:
    16. print("用户名不能为空")
  • 相关阅读:
    本地部署modelscope-agent
    postgresql数据库pg_dirtyread插件闪回技术 —— 筑梦之路
    聊聊 C# 中的 Composite 模式
    【软件测试】测试人填坑?测试工作中的坑成长经历,填着填着就成了神......
    循环神经网络RNN
    计算机毕业设计Java中学后勤设备保修维护管理系统(源码+系统+mysql数据库+lw文档)
    做前端,看完这篇文章你也可以做到
    Rust 学习笔记
    用3D扫描生成合成数据
    向中央超算平台进化 哪吒汽车发布技术品牌“浩智”
  • 原文地址:https://blog.csdn.net/Hudas/article/details/126786629