Python基础:字符串str & 列表list & 元组tuple & 字典dict & 集合set

字符串 str

字符串是以单引号或双引号括起来的任意文本

字符串不可变

创建字符串
str1 = "lee is a good man!"
str2 = "lee is a nice man!"
str3 = "lee is a handsome man!"

字符串运算

字符串拼接

str6 = "lee is a "
str7 = "good man"
str8 = str6 + str7
print("str6 =", str6)
print("str7 =", str7)
print("str8 =", str8)

a="hello"+"-"*50+"world"
print(a)
print(a.__len__())
print(len(a))

输出重复字符串

输出重复字符串
str9 = "good"
str10 = str9 * 3
print("str10 =", str10)

访问字符串中的某一个字符

通过索引下标查找字符
字符串名[下标]
str11 = "lee is a good man!"
print(str11[1])
#str11[1] = "a" #打印会报错,因为字符串不可变
#print("str11 =", str11)

字符串取值(切片)

str12 = "to day is a good day"
print(str12[5:10])      # 从给定下标开始截取到给定下标之前
print(str12[:4])        # 从头截取到给定下标之前
print(str12[14:])       # 从给定下标处开始截取到结尾
print(str12[:])         # :号前后都省略,则表示全取列表所有的值;但这样写比较怪,不如直接print(str12)
print(str12[::2])       # 第一个:号前后都省略,表示全取,第二个:号后的数字2表示步长(和循环里的步长一致)
print(str12[::-1])      #列表反转,类似os.reverse()

字符串判断

str13 = "lee is a good man!"
print("good" in str13)
print("good" not in str13)

格式化输出

print("lee is a good man")
num = 10
str14 = "lee is a nice man!"
f = 10.14567
print("num =", num)
#      %d       %s      %f      占位符
#                                 %.2f 精确到小数后2位,会四舍五入
print("num = %d, str14 = %s, f = %.2f" %(num,str14,f))

字符串的方法

abc=" Hello,nice to meet you "
print(len(abc))                 # 打印字符串的长度
print(abc.__len__())            # 打印字符串的长度
print(abc.lower())              # 转换字符串中大写字母为小写字母
print(abc.upper())              # 转换字符串中小写字母为大写字母
print(abc.swapcase())           # 转换字符串中大写字母为小写字母,小写字母为大写字母
print(abc.capitalize())         # 整个字符串中首字母大写,其他全部小写
print(abc.title())              # 每个单词的首字母大写
print(abc.center(50, "*"))      # 一共50个字符,字符串放中间,不够的两边补*
print(abc.ljust(50, "*"))       # 一共50个字符,字符串放左边,不够的左边补*
print(abc.rjust(50, "*"))       # 一共50个字符,字符串放右边,不够的右边补*
print(abc.zfill(50))            # 一共50个字符,字符串放右边,不够的右边补0
print(abc.count("t"))           # 统计字符串里t出现了多少次
print(abc.find("to"))           # 找出to在字符串中的第几位
print(abc.rfind("to"))          # 找出最后一个to在字符串中的第几位
print(abc.index("to"))          # 和find一样的查找,只不过如果to不存在的时候会报一个异常
print(abc.rindex("to"))         # 和rfind一样的查找,只不过如果to不存在的时候会报一个异常
print(abc.endswith("you"))      # 判断是否以you结尾
print(abc.startswith("Hello"))  # 判断字符串是否以hello开始
print(abc.isalnum())            # 判断字符串中是否只有字母或数字
print(abc.isalpha())            # 判断字符串是否都是字母
print(abc.isdecimal())          # 判断字符串中是否只包含十进制字符
print(abc.isdigit())            # 判断字符串中是否只有数字
print(abc.islower())            # 判断字符串中的字符是否都是小写的英文字母
print(abc.isnumeric())          # 判断字符串中是否只有数字
print(abc.isspace())            # 判断字符串中是否只包含空格

print(abc.strip())              # 去掉字符串左右两端的空格或换行
print(abc.lstrip())             # 去掉字符串左边空格或换行
print(abc.rstrip())             # 去掉字符串右边空格或换行
#   eval(str)
#   功能:将字符串str当成有效的表达式来求值并返回计算结果
print(eval("+123"))
print(eval("-123"))
print(eval("12+3"))
print(eval("12-3"))


#   len(str)
#   返回字符串的长度(字符个数)
print(len("lee is a good man!"))


#   lower()
#   转换字符串中大写字母为小写字母
str15 = "LEE is a Good Man!"
print(str15.lower())


#   upper()
#   转换字符串中小写字母为大写字母
str16 = "LEE is a Good Man!"
print(str16.upper())
print("LEE is a Good Man!".upper())


#   swapcase()
#   转换字符串中大写字母为小写字母,小写字母为大写字母
str17 = "LEE is a Good Man!"
print(str17.swapcase())


#   capitalize()
#   首字母大写,其他小写
str18 = "LEE is a Good Man!"
print(str18.capitalize())


#   title()
#   每个单词的首字母大写
str19 = "LEE is a Good Man!"
print(str19.title())


#   center(width[,fillchar])
#   返回一个指定宽度的居中字符串,fillchar为填充的字符串,默认是空格填充
str20 = "lee is a nice man!"
print(str20.center(40,"*"))


#   ljust(width[,fillchar])
#   返回一个指定宽度的左对齐字符串,fillchar为填充的字符串,默认是空格填充
str21 = "lee is a nice man!"
print(str21.ljust(40,"%"))


#   rjust(width[,fillchar])
#   返回一个指定宽度的右对齐字符串,fillchar为填充的字符串,默认是空格填充
str22 = "lee is a nice man!"
print(str22.rjust(40,"%"))


#   zfill(width)
#   返回一个长度为width的字符串,原字符串右对齐,前面补0
str23 = "lee is a nice man!"
print(str23.zfill(40))


#   count(str[,start][,end])
#   返回字符串中strc出现的次数,可以指定一个范围,默认从头到尾
str24 = "lee is a very very nice man!"
print(str24.count("very"))
print(str24.count("very",9,len(str24)))


#   find(str[,start][,end])
#   从左向右检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾,得到的是第一次出现的开始下标,没有返回-1
str25 = "lee is a very very nice man!"
print(str25.find("very"))
print(str25.find("good"))
print(str25.find("very",8,len(str25)))


#   rfind(str[,start][,end])
str25 = "lee is a very very nice man!"
print(str25.rfind("very"))
print(str25.rfind("good"))
print(str25.rfind("very",8,len(str25)))


#   index(str,start=0,end=len(str))
#   跟find()一样,只不过如果str不存在的时候会报一个异常
str26 = "lee is a very very nice man!"
print(str26.index("very"))


#   rndex(str,start=0,end=len(str))
#   跟rfind()一样,只不过如果str不存在的时候会报一个异常
str27 = "lee is a very very nice man!"
print(str27.rindex("very"))


#   lstrip()
#   截掉字符串左侧指定的字符,默认为空格
str28 = "*******lee is a nice man!"
print(str28.lstrip("*"))


#   rstrip()
#   截掉字符串右侧指定的字符,默认为空格
str29 = "lee is a nice man!       "
print(str29.rstrip(),"*")


#   strip()
#   截掉字符串两侧指定的字符,默认为空格
str30 = "******lee is a nice man******"
print(str30.strip("*"))

# 应用, 模拟用户登录. 忽略用户输入的空格
username = input("请输入用户名:").strip()
password = input("请输入密码: ").strip()
if username == 'xiaobai' and password == '123':
    print("登录成功")
else:
    print("登录失败")



#  split(str="",num)
#  以str为分隔符截取字符串,指定num,则仅截取num个字符串
str31 = "lee***is*****a**good**man"
print(str31.split("*"))
list39 = str31.split("*")
c = 0
for s in list39:
    if len(s) > 0:
        c += 1
print(c)


#  splitlines([keepends])
#  按照('\r', '\r\n', '\n')分割
#  keepends == True  会保留换行符
str32 = '''
lee is a good man!
lee is a nice man!
lee is a handsome man!
'''
print(str32.splitlines())


#   join(seq)
#以指定的字符串分隔符,将seq中的所有元素组合成一个字符串
list33 = ['lee','is','a','good','man']
str33 = " ".join(list33)
print(str33)


#   max() min()
str34 = "lee is a good man z"
print(max(str34))
print("*"+min(str34)+"*")


#   replace(oldstr,newstr,count)
#   用newstr替换oldstr,默认是全部替换。如果指定了count,那么只替换前count个
str35 = "lee is a good good good man"
str36 = str35.replace("good","nice",1)
print(str36)


#   创建一个字符串映射表
#                      要转换的字符串, 目标字符串
str37 = str.maketrans("ac","65")
#   a--6    c--5
str38 = "lee is a good man"
str39 = str38.translate(str37)
print(str39)


#   startswith(str,start=0,end=len(str))
#   在给定的范围内是否是以给定的字符串开头的,如果没有指定范围,默认整个字符串
str40 = "lee is a good man"
print(str40.startswith("lee",5,14))


#   endswith(str,start=0,end=len(str))
#   在给定的范围内是否是以给定的字符串结尾的,如果没有指定范围,默认整个字符串
str41 = "lee is a good man"
print(str41.endswith("man"))


#   编码
#encode(encoding="utf-8",errors="strict")
str42 = "lee is a good man杰"
#ignore 忽略错误
date42 = str42.encode("utf-8","ignore")
print(date42)

#   解码 注意:要与编码时的编码格式一致
str43 = date42.decode("gbk","ignore")
print(str43)


#   isalpha()
#   如果字符串中至少有一个字符且所有的字符都是字母返回True,否则返回False
str44 = "leeisagoodman"
print(str44.isalpha())


#   isalnum()
#   如果字符串中至少有一个字符且所有的字符都是字母或数字返回True,否则返回False
str45 = "12a3"
print(str45.isalnum())


#   isupper()
#   如果字符串中至少有一个英文字符且所有的字符都是大写的英文字母返回True,否则返回False
print("ABD".isupper())
print("AbC".isupper())
print("ABC".isupper())
print("ABD#".isupper())


#   islower()
#   如果字符串中至少有一个英文字符且所有的字符都是小写的英文字母返回True,否则返回False
print("abc".islower())
print("Abcd".islower())
print("ABCD".islower())
print("abc1".islower())
print("abc!".islower())


#   istitle()
#   如果字符串是标题化的返回True,否则返回False
print("Lee Is".istitle())
print("Lee is".istitle())
print("lee is".istitle())


#   isdigit()
#   如果字符串只包含数字字符返回True,否则返回False
print("123".isdigit())
print("123a".isdigit()


#   isnumeric()
#   同上
print("123".isnumeric())
print("123s".isnumeric())


#   isdecimal()
#   字符串中只包含十进制字符
print("123".isdecimal())
print("123a".isdecimal())


#   如果字符串中只包含空格返回True,否则返回False
print(" ".isspace())
print("   ".isspace())
print("\t".isspace())
print("\n".isspace())
print("\r".isspace())
字符串方法示例大全

相关文章: