python中字符串常用方法总结

 初学python,尚有不足之处请批评指正

# 字符串的常用操作
# 1. 大小写转换
str1 = "hellopythonhelloworld"
str2 = "hello python 999, hello world"
str3 = "HELLOpython,HELLOWORLD"

print(str2.title())                 # 返回每个单词首字母大写,其他字母小写的字符串
print(str2.capitalize())        # 返回首字母大写,其他字母全部小写的新字符串

print(str1.upper())     # 将字符串中的每个字母大写
print(str3.lower())        # 将左右字母变小写

print(str3.swapcase())      # 将字符串中的字母大写转小写,小写转大写

# 2. .isxxx 的判断
str1 = "hellopythonhelloworld"
str2 = "hello python 999, hello world"
str3 = "23346546756535"
print(str1.isalpha())          # 判断字符串中是否全是字母(加一个标点符号会是False)
print(str2.isdecimal())      # 检测是否都是数字
print(str1.isdigit())           #检测字符串是否都是数字    (False)
print(str2.isdigit())           #(False)
print(str3.isdigit())           #(True)
print(str2.isnumeric())     # 检测是否都是数字          (这三种方法有区别,如需要,请详查)

str4 = "hellopythonhelloworld666"
print(str4.isalnum())       # 判断字符串是否是字母或数字 ,全是字母(True) 全是数字(True) 字母和数字(True)

str5 =  "                     "
print(str5.isspace())       # 判断是否都是空格

# 3. 查找
print(str4.find("h", 4, 9))       # 查找指定子串的位置,find从左到右查找, 下标(0),    (若找不到则返回-1)
print(str4.rfind("h"))      #rfind从右到左查找,下标 (11) ,也就是从最右边开始找到的子串,但是下标从左边开始,不能混淆

print(str4.index("e"))     # 找到则返回下标,找不到会报错

# 4. 替换
print(str4.replace("hello", "HELLO", 2))     # str.replace(old, new[, count])  count 是替换次数

# 5. 字符串的分割, 并生成一个列表
str5 = "星期一 | 星期二 | 星期三 | 星期四 | 星期五"
print(str5.split("|", 3))       # 可以指定分割次数

print(str5.rsplit("|"))     #rsplit()和split()是一样的,只不过是从右边向左边搜索。

# splitlines()用来专门用来分割换行符。虽然它有点像split('
')或split('
')
# splitlines()中可以指定各种换行符,常见的是
、
、
。如果指定keepends为True,则保留所有的换行符。
str6 = "abc

def 
gh
ijk
"
print(str6.splitlines())                                    # 结果:['abc', '', 'def ', 'gh', 'ijk']
print(str6.splitlines(keepends=True))       # 结果: ['abc
', '
', 'def 
', 'gh
', 'ijk
']

# 6. 去掉空白字符
str7 = "   abcdefghijkl    mn    "
print(str7.lstrip())        # 去掉左边(开始)的空白字符
print(str7.rstrip())        # 去掉右边(末尾)的空白字符
print(str7.strip())         # 去掉两边的空白字符

# 7. 字符串的切片  字符串[开始索引 : 结束索引 :步长值]
# 指定的区间属于左闭右开[开始索引,结束索引)
str8 = "hello python, hello world"
print(str8[6 : 12])
print(str8[6 : : 3])        #ph,eood  步长值就是中间隔 (count-1)个字母再截取

print(str8[: : -1])  # 字符串的逆序

如有疑问,请在下方留言,共同解决

原文地址:https://www.cnblogs.com/mgw2168/p/9476378.html