1.字符串的定义
字符串可以通过
单引号('')
s1 = 'hello world'
双引号("")
s2 = "hello world"
三引号(单引号'''
或双引号"""
)来定义
三引号通常用于定义多行的字符串。
s3 = """
Hello, world!
This is a multi-line string.
"""
2.字符串的遍历
使用for循环遍历
下方代码将得到my_shr中的每一个字符
my_str = "hello world"
#使用for循环遍历得到字符串中的每一个字符
for char in my_str:
print(char)
使用len遍历
a = "hello"
for i in range(len(a)):
print(i, a[i])
得到一下结果
0 h
1 e
2 l
3 l
4 o
3.字符串的常规操作
# print("醒醒" .center(20,"*"))
# print("醒醒".rjust(20,"*"))
# print("醒醒".ljust(20,"*"))
# print("醒醒".zfill(20))
# print("中华人民共和国".endswith("共和国"))
# print("中华人民共和国".startswith("中华"))
#
# s= print("中华人民共和国合同法".split("共和国"))
# print("++".join("中华人民共和国"))
print("python".upper()) #全大写 isupper判断是否字符串中全大写
print("PYTHON".lower()) #全小写 islower判断是否字符串中全小写 isspace判断是否字符串中只包含空格
print("helloworld".capitalize()) #首字母大写
print("hello world".title()) #每个单词的首字母大写
print("中华人民共和国合同法".find("共和国")) #找出”共和国“第一次出现的位置 并返回索引值
print("中华人民共和国合同法".index("共和国")) #同上 并返回索引值
print("你好啊,你多大了".replace("你","大家",1)) #replace用于替换字符,第一个为需要替换的 第二个为替换的内容,count替换第几次出现的
print("hello world".split()) #拆分字符串,返回一个列表
print(" hello world ".strip()) # 用于清除字符串 首尾的空白
print("fhhf".isalpha()) #判断字符串中是否只包含字母 是 返回True 否 返回 False
print("13254654".isdigit())#判断字符串中是否只包含数字,是 返回True 否 返回 False