Python字符串从浅到深

1.字符串的定义

字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。

创建字符串很简单,只要为变量分配一个值即可。例如:

s1 = 'sfsefsf'
s2 = "sfhuse"

Python三引号

python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。实例如下。


 
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str)
结果如下:
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB (    )。
也可以使用换行符 [ 
 ]。

三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。


2.字符串的遍历

Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。

Python 访问子字符串,可以使用方括号 [] 来截取字符串,字符串的截取的语法格式如下:

变量[开始:结束,步长]

从开始位置截取到结束位置,间隔为步长。

索引值以 0 为开始值,-1 为从末尾的开始位置。

s1 = "中华人民共和国合同法"
print(s1[2:7])

一下是运行结果:

3.字符串的常见操作

下表实例变量 a 值为字符串 "Hello",b 变量值为 "Python":

操作符描述实例
+字符串连接a + b 输出结果: HelloPython
*重复输出字符串a*2 输出结果:HelloHello
[]通过索引获取字符串中字符a[1] 输出结果 e
[ : ]截取字符串中的一部分,遵循左闭右开原则,str[0:2] 是不包含第 3 个字符的。a[1:4] 输出结果 ell
in成员运算符 - 如果字符串中包含给定的字符返回 True'H' in a 输出结果 True
not in成员运算符 - 如果字符串中不包含给定的字符返回 True'M' not in a 输出结果 True

一下是运行实例:


 
a = "Hello"
b = "Python"
 
print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])
 
if( "H" in a) :
    print("H 在变量 a 中")
else :
    print("H 不在变量 a 中")
 
if( "M" not in a) :
    print("M 不在变量 a 中")
else :
    print("M 在变量 a 中")
 

以上实例的运行结果如下:

a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中

以下是方法列表

序号

方法及描述
1

capitalize()
将字符串的第一个字符转换为大写

2

center(width, fillchar)

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3

count(str, beg= 0,end=len(string))


返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4

bytes.decode(encoding="utf-8", errors="strict")


Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
5

encode(encoding='UTF-8',errors='strict')


以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
6

endswith(suffix, beg=0, end=len(string))
检查字符串是否以 suffix 结束,如果 beg 或者 end 指定则检查指定的范围内是否以 suffix 结束,如果是,返回 True,否则返回 False。

7

expandtabs(tabsize=8)


把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
8

find(str, beg=0, end=len(string))


检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
9

index(str, beg=0, end=len(string))


跟find()方法一样,只不过如果str不在字符串中会报一个异常。
10

isalnum()


如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
11

isalpha()


如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
12

isdigit()


如果字符串只包含数字则返回 True 否则返回 False..
13

islower()


如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
14

isnumeric()


如果字符串中只包含数字字符,则返回 True,否则返回 False
15

isspace()


如果字符串中只包含空白,则返回 True,否则返回 False.
16

istitle()


如果字符串是标题化的(见 title())则返回 True,否则返回 False
17

isupper()


如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
18

join(seq)


以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
19

len(string)


返回字符串长度
20

ljust(width[, fillchar])


返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
21

lower()


转换字符串中所有大写字符为小写.
22

lstrip()


截掉字符串左边的空格或指定字符。
23

maketrans()


创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
24

max(str)


返回字符串 str 中最大的字母。
25

min(str)


返回字符串 str 中最小的字母。
26

replace(old, new [, max])


把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
27

rfind(str, beg=0,end=len(string))


类似于 find()函数,不过是从右边开始查找.
28

rindex( str, beg=0, end=len(string))


类似于 index(),不过是从右边开始.
29

rjust(width,[, fillchar])


返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
30

rstrip()


删除字符串末尾的空格或指定字符。
31

split(str="", num=string.count(str))


以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
32

splitlines([keepends])


按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
33

startswith(substr, beg=0,end=len(string))


检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
34

strip([chars])


在字符串上执行 lstrip()和 rstrip()
35

swapcase()


将字符串中大写转换为小写,小写转换为大写
36

title()


返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
37

translate(table, deletechars="")


根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
38

upper()


转换字符串中的小写字母为大写
39

zfill (width)


返回长度为 width 的字符串,原字符串右对齐,前面填充0
40

isdecimal()


检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

以下是对上述字符串方法的详细解释和示例:

1. capitalize()

string = "hello world"
capitalized_string = string.capitalize()
print(capitalized_string)  # 输出: "Hello world"

2. center(width, fillchar)

string = "hello"
centered_string = string.center(10, '*')
print(centered_string)  # 输出: "**hello***"

3. count(str, beg= 0, end=len(string))

string = "hello world"
count = string.count('l')
print(count)  # 输出: 3

4. bytes.decode(encoding="utf-8", errors="strict")

encoded_bytes = "hello".encode('utf-8')
decoded_string = encoded_bytes.decode('utf-8')
print(decoded_string)  # 输出: "hello"

5. encode(encoding='UTF-8', errors='strict')

string = "你好"
encoded_bytes = string.encode('utf-8')
print(encoded_bytes)  # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'

6. endswith(suffix, beg=0, end=len(string))

string = "hello world"
result = string.endswith("world")
print(result)  # 输出: True

7. expandtabs(tabsize=8)

string = "hello\tworld"
expanded_string = string.expandtabs()
print(expanded_string)  # 输出: "hello       world"

8. find(str, beg=0, end=len(string))

string = "hello world"
index = string.find('world')
print(index)  # 输出: 6

9. index(str, beg=0, end=len(string))

string = "hello world"
try:
    index = string.index('world')
    print(index)
except ValueError:
    print("未找到")

10. isalnum()

string = "hello123"
result = string.isalnum()
print(result)  # 输出: True

11. isalpha()

string = "hello"
result = string.isalpha()
print(result)  # 输出: True

12. isdigit()

string = "123"
result = string.isdigit()
print(result)  # 输出: True

13. islower()

string = "hello"
result = string.islower()
print(result)  # 输出: True

14. isnumeric()

string = "12345"
result = string.isnumeric()
print(result)  # 输出: True

15. isspace()

string = "  "
result = string.isspace()
print(result)  # 输出: True

16. istitle()

string = "Hello World"
result = string.istitle()
print(result)  # 输出: True

17. isupper()

string = "HELLO"
result = string.isupper()
print(result)  # 输出: True

18. join(seq)

seq = ["hello", "world"]
joined_string = " ".join(seq)
print(joined_string)  # 输出: "hello world"

19. len(string)

string = "hello"
length = len(string)
print(length)  # 输出: 5

20. ljust(width[, fillchar])

string = "hello"
left_justified_string = string.ljust(10, '*')
print(left_justified_string)  # 输出: "hello*****"

21. lower()

string = "HELLO"
lowercase_string = string.lower()
print(lowercase_string)  # 输出: "hello"

22. lstrip()

string = "   hello"
stripped_string = string.lstrip()
print(stripped_string)  # 输出: "hello"

23. maketrans()

from string import maketrans

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

string = "hello world"
translated_string = string.translate(trantab)
print(translated_string)  # 输出: "h2ll4 w4rld"

24. max(str)

string = "hello"
max_char = max(string)
print(max_char)  # 输出: 'o'

25. min(str)

string = "hello"
min_char = min(string)
print(min_char)  # 输出: 'e'

26. replace(old, new [, max])

string = "hello world"
new_string = string.replace('world', 'python', 1)
print(new_string)  # 输出: "hello python"

27. rfind(str, beg=0, end=len(string))

string = "hello world world"
index = string.rfind('world')
print(index)  # 输出: 12

28. rindex(str, beg=0, end=len(string))

string = "hello world world"
try:
    index = string.rindex('world')
    print(index)
except ValueError:
    print("未找到")

29. rjust(width,[, fillchar])

string = "hello"
right_justified_string = string.rjust(10, '*')
print(right_justified_string)  # 输出: "*****hello"

30. rstrip()

string = "hello   "
stripped_string = string.rstrip()
print(stripped_string)  # 输出: "hello"

31. split(str="", num=string.count(str))

string = "hello world"
split_string = string.split()
print(split_string)  # 输出: ['hello', 'world']

32. splitlines([keepends])

string = "hello\nworld"
split_lines = string.splitlines()
print(split_lines)  # 输出: ['hello', 'world']

33. startswith(substr, beg=0, end=len(string))

string = "hello world"
result = string.startswith("hello")
print(result)  # 输出: True

34. strip([chars])

string = "   hello   "
stripped_string = string.strip()
print(stripped_string)  # 输出: "hello"

35. swapcase()

string = "Hello WORLD"
swapped_case_string = string.swapcase()
print(swapped_case_string)  # 输出: "hELLO world"

36. title()

string = "hello world"
title_string = string.title()
print(title_string)  # 输出: "Hello World"

37. translate(table, deletechars="")

from string import maketrans

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

string = "hello world"
translated_string = string.translate(trantab)
print(translated_string)  # 输出: "h2ll4 w4rld"

38. upper()

string = "hello"
uppercase_string = string.upper()
print(uppercase_string)  # 输出: "HELLO"

39. zfill (width)

string = "123"
filled_string = string.zfill(5)
print(filled_string)  # 输出: "00123"

40. isdecimal()

string = "123"
result = string.isdecimal()
print(result)  # 输出: True

制作不易,请多多三连,谢谢。

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值