python字符串(string)

字符串

字符串的组成

  • 字符串是由一系列字符组成的有序序列
  • 字符串是不可修改的序列
  • 字符串是由’‘,“”,’‘’‘’'(单引号,双引号,三引号)括起来的
  • 字符串可以使用[]对其中元素进行访问
# 以下是几种字符串的表示。
'hello'
"world"
# 三引号主要适用于括起一个段落,可换行
'''hello world 
python3
haha'''
# 将字符串对象赋值给变量s
s = "hello world"
print(s)
# 使用[]访问字符串
print("s[0] is",s[0])
print("s[1] is",s[1])
hello world
s[0] is h
s[1] is e

单引号和双引号的选择

# 当字符串中包含单引号'时,可以使用\来专一字符
print('I\'m a boy!')
# 也可以使用""来包括带有单引号的字符串
print("I'm a boy!")

# 当字符串中包含双引号"时,可以使用\来专一字符
print("I\"m a boy!")
# 也可以使用''来包括带有双引号的字符串
print('I"m a boy!')
I'm  student!
I'm  student!
I"m  student!
I"m  student!

字符串的访问

  • 使用下标访问
s = "hello world"
print(s[0])
h
  • 切片访问
# 字符串是个有序的序列,可以使用切片访问
print(s[1:5])
print(s[1::2])
print(s[:8:3])
ello
el ol
hlw
  • 遍历字符串
for c in s:
    print(c)
h
e
l
l
o
 
w
o
r
l
d
  • 字符串不可修改
s = "hello"
s[0] = 'c'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_2036/2672832050.py in <module>
      1 s = "hello"
----> 2 s[0] = 'c'


TypeError: 'str' object does not support item assignment

字符串运算

  • +、*
s = "asd"
s1 = "qwe"
s2 = s + s1
print(s2)
s2 = s * 3
print(s2)
asdqwe
asdasdasd
  • 比较运算
# ==、!=、>=、<=、>、<
print("abd" == "abd")
print("abd" != "abd")
print("abd" >= "cde")
print("abd" <= "cde")
print("afd" > "cbe")
print("afd" < "ade")
True
False
False
True
False
False
  • in 、not in

    str1 in str2 判断str1在str2中包含,返回True

    str1 in str2 判断str1不在str2中包含,返回True

print("asd" in "asdf")
print("asd" in "asf")
print("asd" not in "asdf")
print("asd" not in "asf")
True
False
False
True

字符串的方法

  • len()
# 返回字符串长度
s = "hello"
print(len(s))
5
  • count()

str.count(sub[, start[, end]])

返回子字符串 sub 在 [start, end] 范围内非重叠出现的次数.[start, end] 切片表示,是可选参数

s = "asdasdasasasd"
print(s.count('as'))
print(s.count('as',1,))
print(s.count('as',1,7))
5
4
1
  • center()

str.center(width[, fillchar])

返回长度为 width 的字符串,str居中,两边用fillchar填充(默认是空格),当width小于len(str)时,返回str

s = "abcasdasd123"
print(s.center(20))
print(s.center(20,'*'))
print(s.center(10,'*'))
    abcasdasd123    
****abcasdasd123****
abcasdasd123
  • str.capitalize()

返回原字符串的副本,其首个字符大写,其余为小写。

s = "hello"
print(s.capitalize())
Hello
  • string.casefold()

将字符串转换为小写

s = "HeLLo"
print(s.casefold())
hello
  • str.encode(encoding=‘utf-8’, errors=‘strict’)

设置字符串编码格式,默认是utf-8

  • str.endswith(suffix[, start[, end]])

如果字符串以指定的 suffix 结束返回 True,否则返回 False。start[, end],为切片表示

s = "Hello"
print(s.endswith("l"))
print(s.endswith(("l","lo")))
print(s.endswith(("l","lo"),1))
print(s.endswith(("lo"),0,3))
False
True
True
False
  • str.find(sub[, start[, end]])

返回子字符串 sub 在 s[start:end] 切片内被找到的最小索引。 可选参数 start 与 end 会被解读为切片表示法。 如果 sub 未被找到则返回 -1。

s = "Hello"
print(s.find("l"))
print(s.find("el",1,4))
print(s.find("L"))
2
1
-1
  • str.rfind(sub[, start[, end]])

返回子字符串 sub 在字符串内被找到的最大(最右)索引

s = "Hellollloo"
print(s.rfind("lo"))
print(s.rfind("lo",1,6))
print(s.rfind("L"))
7
3
-1
  • str.format()

格式化输出字符串(边用边查)

print("1 + 1 = {}".format(1+1))
# 按照指定顺序输出
print("{0},{1}".format("hello","xian"))
print("{0},{1},{1},{0}".format("hello","xian"))

print("name is {name}, age is {age}".format(name = "zhangsan",age = 20))
# 字典格式输出
d = {"name":"li" , "age":18}
print("name is {name}, age is {age}".format(**d))

# 列表格式输出
l = ["lisi", 18]
print("name is {0[0]}, age is {0[1]}".format(l))

# 数字格式化输出
print("{:,}".format(1000000)) #逗号间隔
print("{:.2%}".format(25)) #百分比输出
print("{:>5d}".format(15)) #右对齐
print("{:<5d}".format(15)) #左对齐
print("{:^5d}".format(15)) #居中对齐
print('{:b}'.format(15)) #二进制
print('{:d}'.format(15)) #十进制
print('{:o}'.format(15)) #八进制
print('{:x}'.format(15)) #十六进制
print('{:#x}'.format(15)) #十六进制小写带0x
print('{:#X}'.format(15)) #十六进制大写带0X
1 + 1 = 2
hello,xian
hello,xian,xian,hello
name is zhangsan, age is 20
name is li, age is 18
name is lisi, age is 18
1,000,000
2500.00%
   15
15   
 15  
1111
15
17
f
0xf
0XF
  • str.index(sub[, start[, end]])

类似于 find(),但在找不到子字符串时会引发 ValueError

s = "hello"
print(s.index("l"))
print(s.index("W"))
2



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_2036/2323225845.py in <module>
      1 s = "hello"
      2 print(s.index("l"))
----> 3 print(s.index("W"))


ValueError: substring not found
  • str.rindex(sub[, start[, end]])

类似于 rfind(),但在子字符串 sub 未找到时会引发 ValueError。

s = "hello"
print(s.rindex("l"))
print(s.rindex("W"))
3



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_2036/4168776423.py in <module>
      1 s = "hello"
      2 print(s.rindex("l"))
----> 3 print(s.rindex("W"))


ValueError: substring not found
  • str.isalnum()

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

  • str.isalpha()

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

  • str.isascii()

如果字符串为空或字符串中的所有字符都是 ASCII(0~0x7f) ,返回 True ,否则返回 False

  • str.isdecimal()

如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符,则返回 True , 否则返回 False

  • str.isdigit()

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

  • str.isidentifier()

如果字符串是有效的标识符,返回 True

  • str.islower()

如果字符串中至少有一个区分大小写的字符 4 且此类字符均为小写则返回 True ,否则返回 False

  • str.isnumeric()

如果字符串中至少有一个字符且所有字符均为数值字符则返回 True ,否则返回 False

  • str.isprintable()

如果字符串中所有字符均为可打印字符或字符串为空则返回 True ,否则返回 False

  • str.isspace()

如果字符串中只有空白字符且至少有一个字符则返回 True ,否则返回 False

  • str.istitle()

如果字符串中至少有一个字符且为标题字符串则返回 True

  • str.isupper()

如果字符串中至少有一个区分大小写的字符 4 且此类字符均为大写则返回 True ,否则返回 False

#True
print("hello".isalnum())
#False
print("he22!lo".isalnum())
#True
print("hello".isalpha())
#False
print("he22lo".isalpha())
#True
print("hello".isascii())
#True
print("he22l`o".isascii())
#True
print("12342".isdecimal())
#False
print("123a".isdecimal())
#True
print("12342".isdigit())
#False
print("123a".isdigit())
#False
print("1234aa_2".isidentifier())
#False
print("123!a".isidentifier())
#True
print("1234aa_2".islower())
#False
print("123!aS".islower())
#False
print("1234a2".isnumeric())
#False
print("123!a".isnumeric())
#True
print("1234aa_2".isprintable())
#False
print("123!a\n".isprintable())
#False
print("1234a a_2".isspace())
#False
print("123!  a".isspace())
#True
print("Hello".istitle())
#False
print("hEllo".istitle())
#True
print("H2344".isupper())
#False
print("hE2345".isupper())

True
False
True
False
True
True
True
False
True
False
False
False
True
False
False
False
True
False
False
False
True
False
True
False
  • str.replace(old, new[, count])

返回字符串的副本,其中出现的所有子字符串 old 都将被替换为 new。 如果给出了可选参数 count,则只替换前 count 次出现

print("helloooollll".replace('l','o'))
print("helloooollll".replace('l','o',3))
heoooooooooo
heooooooolll
  • str.join(iterable)

返回一个由 iterable 中的字符串拼接而成的字符串

print("hello".join("world")) # hello 是间隔符"
print("-".join("world")) # - 是间隔符"
whelloohellorhellolhellod
w-o-r-l-d
  • str.ljust(width[, fillchar])

返回长度为 width 的字符串,原字符串在其中靠左对齐

  • str.rjust(width[, fillchar])

返回长度为 width 的字符串,原字符串在其中靠右对齐

print("hello".ljust(10,"*"))
print("hello".rjust(10,'^'))
hello*****
^^^^^hello
  • str.split(sep=None, maxsplit=- 1)

返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit,则最多进行 maxsplit 次拆分

  • str.rsplit(sep=None, maxsplit=- 1)

返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit,则最多进行 maxsplit 次拆分,从 最右边 开始

print("h j k l j".split(" "))
print("h j k l j".split(" ",3))
print("h j k l j".rsplit(" "))
print("h j k l j".rsplit(" ",3))
['h', 'j', 'k', 'l', 'j']
['h', 'j', 'k', 'l j']
['h', 'j', 'k', 'l', 'j']
['h j', 'k', 'l', 'j']
  • str.strip([chars])

返回原字符串的副本,移除其中的前导和末尾字符。 chars 参数为指定要移除字符的字符串。 如果省略或为 None,则 chars 参数默认移除空白符。 实际上 chars 参数并非指定单个前缀或后缀;而是会移除参数值的所有组合

print("  H hu jjh  ".strip())
print("www.baidu.com".strip("cmow."))
H hu jjh
baidu

字符串和列表

  • 字符串到列表 --> split()/rsplit() 、 list()

  • 列表到字符串 --> join() 可指定分隔符 、 str

s = "h e llo"
l = s.split(" ")
print(l,type(l))
l = list(s)
print(l,type(l))

l = ["hk", "kl", " ko"]
s = "".join(l)
print(s,type(s))
s = str(l)
print(s,type(s))
['h', 'e', 'llo'] <class 'list'>
['h', ' ', 'e', ' ', 'l', 'l', 'o'] <class 'list'>
hkkl ko <class 'str'>
['hk', 'kl', ' ko'] <class 'str'>

字符串和字典

  • 字符串到字典
    • 使用json -> str, json.loads()
    • 使用literal_eval -->import ast ast.literal_eval(str)
  • 字典到字符串
    • 使用json -> dict json.dumps()
    • 使用str()方法
import json
d = {"name":"lisi","age":15}
s = json.dumps(d)
print(s,type(s))

s = str(d)
print(s,type(s))
{"name": "lisi", "age": 15} <class 'str'>
{'name': 'lisi', 'age': 15} <class 'str'>
import json
import ast
s = '{"name":"lisi","age":15}'
# 字符串里面字段的key/value只能用双引号
d = json.loads(s)
print(d,type(d))

d = ast.literal_eval(s)
print(d,type(d))
{'name': 'lisi', 'age': 15} <class 'dict'>
{'name': 'lisi', 'age': 15} <class 'dict'>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ghost_199503

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值