「Python」字符串操作内置函数

目录:

  1. capitalize
  2. casefold
  3. center
  4. count
  5. encode
  6. decode
  7. endswith
  8. expandtabs
  9. find
  10. format
  11. format_map
  12. index
  13. isalnum
  14. isalpha
  15. isdecimal
  16. isdigit
  17. isidentifier
  18. islower
  19. isnumeric
  20. isprintable
  21. isspace
  22. istitle
  23. isupper
  24. join
  25. ljust
  26. lower
  27. lstrip
  28. maketrans
  29. partition
  30. replace
  31. rfind
  32. rindex
  33. rjust
  34. rpartition
  35. rsplit
  36. rstrip
  37. split
  38. splitlines
  39. startswith
  40. strip
  41. swapcase
  42. title
  43. translate
  44. upper
  45. zfill

1.0 capitalize()函数

描述:将字符串的第一个字母变成大写,其余字母变为小写。

语法:str.capitalize() —> str 返回字符串

str1 = "i Love python"
str2 = " i Love python" #字母i前有空格
str3 = "I Love python"
print(str1.capitalize())
print(str2.capitalize())
print(str3.capitalize())

程序运行结果:

I love python
i love python
I love python

2.0 lower()函数

描述:将字符串中的所有大写字母转换为小写字母。

语法:str.lower() -> str 返回字符串

str1 = "I Love Python"
str2 = "Groß - α" #德语 大写α
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())

程序运行结果:

i love python
i love python
gross - α
groß - α

注意

lower()函数和casefold()函数的区别:

lower() 方法只对ASCII编码,即‘A-Z’有效,对于其它语言中把大写转换为小写的情况无效,只能用 casefold() 函数。

 

3.0 casefold()函数

描述:将字符串中的所有大写字母转换为小写字母。

语法:str.casefold() -> str 返回字符串

str1 = "I Love Python"
str2 = "Groß - α" #德语 大写α
print(str1.casefold())
print(str1.lower())
print(str2.casefold())
print(str2.lower())

程序运行结果:

i love python
i love python
gross - α
groß - α

4.0 center()函数

描述:返回一个长度为width,两边用fillchar(单字符)填充的字符串,即字符串str居中,两边用fillchar填充。若字符串的长度大于width,则直接返回字符串str

语法:str.center(width , "fillchar") -> str 返回字符串 注意:引号不可省

str = "i love python"
print(str.center(20,"*"))
print(str.center(1,"*"))
print(str.center(20,"8"))

程序运行结果:

***i love python****
i love python
888i love python8888

5.0 count()函数

描述:统计字符串里某个字符出现的次数。可以选择字符串索引的起始位置和结束位置。 

语法:str.count("char", start,end) 或 str.count("char") -> int 返回整数

str为要统计的字符(可以是单字符,也可以是多字符),star为索引字符串的起始位置,默认参数为0,end为索引字符串的结束位置,默认参数为字符串长度即len(str)

str = "i love python,i am learning python"
print(str.count("i")) #star 和end 为默认参数
print(str.count("i",2)) # star值为2,end值为默认参数
print(str.count("i",2,5)) #star值为2,end值为5
print(str.count("am")) #多字符统计

程序运行结果:

3
2
0
1

6.0 encode()函数

描述:以指定的编码格式编码字符串,默认编码为 'utf-8'。

语法:str.encode(encoding='utf-8', errors='strict') -> bytes (获得bytes类型对象)

  • encoding 参数可选,即要使用的编码,默认编码为 'utf-8'。字符串编码常用类型有:utf-8,gb2312,cp936,gbk等。
  • errors 参数可选,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeEncodeError。 其它可能值有 'ignore', 'replace', 'xmlcharrefreplace'以及通过 codecs.register_error() 注册其它的值。
str1 = "我爱祖国"
str2 = "I love my country"
print("utf8编码:",str1.encode(encoding="utf8",errors="strict")) #等价于print("utf8编码:",str1.encode("utf8"))
print("utf8编码:",str2.encode(encoding="utf8",errors="strict"))
print("gb2312编码:",str1.encode(encoding="gb2312",errors="strict"))#以gb2312编码格式对str1进行编码,获得bytes类型对象的str
print("gb2312编码:",str2.encode(encoding="gb2312",errors="strict"))
print("cp936编码:",str1.encode(encoding="cp936",errors="strict"))
print("cp936编码:",str2.encode(encoding="cp936",errors="strict"))
print("gbk编码:",str1.encode(encoding="gbk",errors="strict"))
print("gbk编码:",str2.encode(encoding="gbk",errors="strict"))

程序运行结果:

utf8编码: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
utf8编码: b'I love my country'
gb2312编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gb2312编码: b'I love my country'
cp936编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
cp936编码: b'I love my country'
gbk编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gbk编码: b'I love my country'

注:在python中encode和decode分别指编码和解码

7.0 decode()函数

描述:以 encoding 指定的编码格式解码字符串,默认编码为字符串编码。

  • encoding ——要使用的编码,如:utf-8,gb2312,cp936,gbk等。
  • errors ——设置不同解码错误的处理方案。默认为 'strict',意为编码错误引起一个 UnicodeDecodeError。 其它可能得值有 'ignore', 'replace'以及通过 codecs.register_error() 注册的1其它值。

语法:str.decode(encoding='utf-8', errors='strict')

s = "我爱祖国"
str1 = s.encode(encoding="utf-8",errors="strict")
str2 = s.encode("gb2312") #编码错误的处理方案默认为"strict"
str3 = s.encode("gbk")
print(str1.decode(encoding="utf-8",errors="strict"))#用utf-8的解码格式,解码str1.
print(str1.decode(encoding="gbk",errors="ignore"))##如果以gbk的解码格式对str1进行解码得,将无法还原原来的字符串内容
print(str1.decode(encoding="gbk",errors="strict"))
print(str1.decode(encoding="gbk",errors="replace"))
print(" ")
print(str2.decode("gb2312"))
print(str3.decode("gbk"))

程序运行结果:

我爱祖国
鎴戠埍绁栧浗
鎴戠埍绁栧浗
鎴戠埍绁栧浗
我爱祖国
我爱祖国

8.0 endswith()函数

描述:判断字符串是否以指定字符或子字符串结尾。

语法:str.endswith("suffix", start, end) 或

str[start,end].endswith("suffix") 用于判断字符串中某段字符串是否以指定字符或子字符串结尾。

—> bool 返回值为布尔类型(True,False)

  • suffix — 后缀,可以是单个字符,也可以是字符串,还可以是元组("suffix"中的引号要省略,常用于判断文件类型)。
  • start —索引字符串的起始位置。
  • end — 索引字符串的结束位置。
  • str.endswith(suffix) star默认为0,end默认为字符串的长度减一(len(str)-1)

注意:空字符的情况。返回值通常为True

str = "i love python"
print("1:",str.endswith("n"))
print("2:",str.endswith("python"))
print("3:",str.endswith("n",0,6))# 索引 i love 是否以“n”结尾。
print("4:",str.endswith("")) #空字符
print("5:",str[0:6].endswith("n")) # 只索引 i love
print("6:",str[0:6].endswith("e"))
print("7:",str[0:6].endswith(""))
print("8:",str.endswith(("n","z")))#遍历元组的元素,存在即返回True,否者返回False
print("9:",str.endswith(("k","m")))
#元组案例
file = "python.txt"
if file.endswith("txt"):
print("该文件是文本文件")
elif file.endswith(("AVI","WMV","RM")):
print("该文件为视频文件")
else:
print("文件格式未知")

程序运行结果:

1: True
2: True
3: False
4: True
5: False
6: True
7: True
8: True
9: False
该文件是文本文件

9.0 startswith()函数

描述:判断字符串是否以指定字符或子字符串开头。

语法:str.endswith("suffix", start, end) 或

str[start,end].endswith("suffix") 用于判断字符串中某段字符串是否以指定字符或子字符串结尾。

—> bool 返回值为布尔类型(True,False)

  • suffix — 后缀,可以是单个字符,也可以是字符串,还可以是元组("suffix"中的引号要省略)。
  • start —索引字符串的起始位置。
  • end — 索引字符串的结束位置。
  • str.endswith(suffix) star默认为0,end默认为字符串的长度减一(len(str)-1)

注意:空字符的情况。返回值通常也为True

str = "hello,i love python"
print("1:",str.startswith("h"))
print("2:",str.startswith("l",2,10))# 索引 llo,i lo 是否以“n”结尾。
print("3:",str.startswith("")) #空字符
print("4:",str[0:6].startswith("h")) # 只索引 hello,
print("5:",str[0:6].startswith("e"))
print("6:",str[0:6].startswith(""))
print("7:",str.startswith(("h","z")))#遍历元组的元素,存在即返回True,否者返回False
print("8:",str.startswith(("k","m")))

程序运行结果:

1: True
2: True
3: True
4: True
5: False
6: True
7: True
8: False

10.0 expandtabs()函数

描述:返回一个字符串的副本。使原字符串中的制表符(" ")的使用空间变大。使用空格来扩展空间。

语法: str.expandtabs(tabsize=8) —> str 返回字符串

  • tabsize 的默认值为8。tabsize值为0到7等效于tabsize=8。tabsize每增加1,原字符串中“ ”的空间会多加一个空格。
str = "i love	python"
print(str.expandtabs())#默认值为8
print(str.expandtabs(tabsize=8))
print(str.expandtabs())
print(str.expandtabs(2)) #tabsize值为0到7,与tabsize值为8相同
print(str.expandtabs(tabsize=2))
print(str.expandtabs(tabsize=9))
print(str.expandtabs(tabsize=10))

程序运行结果:

i love python
i love python
i love python
i love python
i love python
i love python
i love python

猜你喜欢

转载自www.cnblogs.com/wrxblog/p/9752400.html