#字符串拼接 +
str1 = "第一个str"
str2 = "第二个str"
print(str1+str2)
# 输出:第一个str第二个str
#输出多个相同字符串
str3 = "good"
str4 = str3*3
print(str4)
# 输出:goodgoodgood
#通过下标访问字符串的某一字符
str5 = "hello world!"
print(str5[4])
#字符串不可更改,不可变
# str5[4] = 'a'
# print(str5)
# 输出:o
#截取字符串中的一部分
str6 = str5[6:11]
print(str6)
#截取从头到某一位置
str6 = str5[:5]
print(str6)
#截取从某一位置到结尾
str6 = str5[6:]
print(str6)
# 输出: world
# hello
# world!
#判断字符串中是否有给定字符串(如果有返回True,没有返回False)
str7 = "he"
print("world" in str5)
print(str7 in str5)
print("ho" in str5)
# 输出: true
# true
# false
#字符串内换行
print("hello\nworld!")
#字符串中有很多换行,用\n不好阅读且繁琐(用''' ''')
print('''
hello
world!
''')
# 输出: hello
# world!
#
# hello
# world!
#如果字符串中有很多字符都需要转义,需要添加很多 " \ " , python允许用r表示内部的字符串默认不转义
print("\\t\\")
print("\\\t\\")
print(r"\\\t\\")
# 输出: \t\
# \ \
# \\\t\\
#eval(str)
#将字符串str当成有效的表达式求值并返回计算结果
print(eval("123"))
print(eval("+123"))
print(eval("-123"))
#print(int("12-3")) #报错 因为"12-3"是字符串
print(eval("12-3")) #能进行字符串内运算
print(eval("12+3"))
# 输出:
# 123
# 123
# -123
# 9
# 15
# len()
#返回字符串的长度(字符个数)
print(len(str5))
# 输出:12
# lower()
#转换字符串中的大写字母到小写字母, 返回一个字符串是小写的,但是原字符串不变
str7 = "HELLO woRLd!"
print(str7.lower())
# 输出:hello world!
#upper
#转换字符串中的小写字母到大写字母, 返回一个字符串是大写的,但是原字符串不变
print(str7.upper())
# 输出:HELLO WORLD!
#swapcase
#字符串中的大小写转换(大写变小写,小写变大写)
print(str7.swapcase())
# 输出:hello WOrlD!
#capitalize
#字符串中只有首字母大写,其余小写
print(str7.capitalize())
# 输出:Hello world!
#title
#字符串中每个单词的首字母大写
print(str7.title())
# 输出:Hello World!
#center(width,fillchar)
#居中填充,用字符填充到足够长度
print(str5.center(40,"*"))
# 输出:**************hello world!**************
#ljuist(width,[,fillchar])
#左对齐填充,默认空格填充
print(str5.ljust(40,"*"))
# 输出:hello world!****************************
#rjuist(width,[,fillchar])
#右对齐填充,默认空格填充
print(str5.rjust(40,"*"))
# 输出:****************************hello world!
# zfill()
#zero fill 用0填充 右对齐
print(str5.zfill(40))
# 输出:0000000000000000000000000000hello world!
# count(str[,start][,end])
#查询字符串中某字符串的个数
print(str5.count("l"))
#查询字符串中范围内某字符串的个数
print(str5.count("l",5,10))
# 输出: 3 1
# find()
# 检测字符串是否包含某字符串,可以指定范围,默认从头到尾,得到第一次出现的下标,没有返回-1
print(str5.find("l"))
print(str5.find("l",0,5))
# 输出; 2 2
# rfind()
# 从右往左找
print(str5.rfind("l"))
# 输出: 9
# index()
# 和find方法一样,如果没有报错,不返回-1
print(str5.index("l"))
# rindex
# 从右往左找
print(str5.rindex("l"))
# 输出:2 9
# lstrip()
# 截掉字符串左侧指定字符,默认为空格
str8 = " hello world!"
str9 = "****hello world"
print(str8.lstrip())
print(str9.lstrip("*"))
# rstrip
# 截掉字符串右侧指定字符,默认为空格
# strip
# 截掉字符串左右两侧指定字符,默认为空格
# 输出:
# hello world!
# hello world
还没有评论,来说两句吧...