1. 字符串创建与基本操作
可使用单引号、双引号来创建字符串,同时可以对字符串执行拼接、重复等操作。
1.单引号,双引号 ,三引号(一般用于特殊格式,比如文档注释)
2.可以交替使用单双引号
3.单行不超过120个字符
s0 = "hello"
s1 = 'hi'
# 嵌套使用
s2 = "hello w'o'rld"
s3 = 'hello w"o"rld'
拼接:
# 拼接
print("hello" + "world")
重复 和长度:
# len 长度
s5 = "hello world"
print(len(s5))
# 重复
print("hello" * 5)
2. 字符串切片
借助切片操作,能够从字符串中提取子串。
# start 默认为0 [:stop]
# stop 默认到最后 [start:]
# step 默认为1 [start:stop:]
s = "hello world"
print(s[0],type(s[0]))
print(s[0:],type(s[0:]))
print(s[0:7])
print(s[6::2])
print(s[-1])
print(s[::-1])
print(s[7:2:-1])
3. 字符串常用方法
Python 的字符串提供了大量实用的方法。
下面是一些常用的例子:
# 统计出现次数
print("快醒醒啦,要吃饭了".count("醒"))
# 返回索引
print("快醒醒啦,要吃饭了".index("醒", 0, 7))
print("快醒醒啦,要吃饭了".rindex("醒", 0, 7))
print("快醒醒啦,要吃饭了".find("醒", 0, 7))
print("快醒醒啦,要吃饭了".rfind("醒", 0, 7))
# 大小写转换
# 首字母大写
print("hello woRld".capitalize())
# # 全大写
print("hello woRld".upper())
# # 全小写
print("hello woRld".lower())
# # 大小写转换
print("hello woRld".swapcase())
# 单词首字母大写
print("hello woRld".title())
# 位置
# 居中
print("***11".center(20,"0"))
# # 居左
print("***11".ljust(20,"2"))
# 居右
print("***11".rjust(20,"2"))
# 填充0 居右
print("***11".zfill(20))
# 开头结尾
print("快醒醒啦,要吃饭了".startswith("吃",0, 7))
print("快醒醒啦,要吃饭了".endswith("吃",0, 7))
# 拼接与切割
# 切割
print("hello world china".split())
# 拼接
print(",".join(['hello', 'world', 'china']))
# 剔除空白
print(" hello world china ".strip())
print(" hello world china ".lstrip())
print(" hello world china ".rstrip())
# 替换
print("hello world china".replace("l","x", 1))
运行结果:
4.字符串编码与解码
字符串可以在不同的编码格式之间进行转换。
s = "hello world up 我是机器"
print(s, type(s))
# encode 编码 decode 解码
s= s.encode(encoding="utf8")
print(s, type(s))
s= s.decode(encoding="utf8")
print(s, type(s))
运行结果:
这些都是 Python 中字符串的基础操作,熟练掌握它们有助于你更高效地处理文本数据。