1.数学运算:+,*
1)字符串1+字符串2 -将两个字符串拼接在一起产生一个新的字符串
注意:字符串只能和字符串相加
str1 = "abc" + "123"
print(str1)
str2 = "how"
str3 = "are"
str4 = str2+str3
print(str4,str2,str3)
# print("abc"+123) # TypeError:must be str,not int
2)字符串N/N字符串 - 字符串重复N次产生一个新的字符串
print("abc"*3) # abcabcabc
print(4*"123") # 123123123123
2.比较运算:==,!=
print("abc "=="abc") # True
print("abc"!="acb") # True
2)比较大小:>,<,>=,<=
** 字符串比较大小,比较的是字符串第一对不相等的字符的编码值的大小
print("abcedf"> "bc") #False
print("abc" > "aac" ) # True
print("Z" > "a") # False
print("z" > "a") # True
print("abc" > "abcd") # False
** a.判断一个字符是否是大写字母,是否是小写字母,是否是中文等···**
小写字母:"a"<= 字符<="z"
中文:"\u4e00" <= 字符 <= "\u9fa5"
数字:"0" <= 数字 <="9"
练习:1)统计一个字符串中小写字母的个数
2)统计一个字符串中汉字的个数
count1 = 0
count2 = 0
count3 = 0
for item in str4:
if "a" <= item <= "z":
count1 +=1
if "A" <= item <= "Z":
count2 += 1
if "\u4e00" <= item <= "\u9fa5":
count3 += 1
print("大写字母的个数为:",count1)
print("小写字母的个数为:",count2)
print("中文个数:",count3)
3) 统计字母的个数
count4 = 0
for item in str4:
if "A" <= item <="Z" or "a" <= item <="z":
count4 +=1
print("字母的个数为:",count4)
3.in / not in
字符串1 in 字符串2 - 判断字符串2中是否包含字符串1
字符串1 not in 字符串2 - 判断字符串2中是否不包含字符串1
print("abc" in "123abc") # True
print("abc" in "a12b3c") # False
print("0" in "红色经典2301") # True
4.len()
** len(序列) - ensp;获取序列的长度(序列中元素的个数)
print(len("ajshdjkfas")) # 10
5.str(数据) - 将指定数据转换成字符串
所有的数据都可以转换成字符串;直接在数据的外面加引号
num = 100
num_str = str(num)
print(len(num_str))
print(num_str[::-1])
6.格式字符串:在字符串中用格式占位符来表示字符串中变化的部分
1)语法
包含格式占位符的字符串 % (格式占位符对应的多个数据)
%s - 字符串
%d - 整数
%.Nf - 小数,N用来约束小数的位数
%c - 字符(可以将数字转换成字符)
name = input("姓名:")
age = int(input("年龄:"))
# message = "我是XXX,今年XX岁"
# message = "我是"+name+",今年"+str(age)+"岁"
message = "我是%s,今年%d岁,月薪:%.3f,等级:%c"%(name,age,10000.5,65)
print(message)
7.字符串相关的方法
字符串.函数名()
1)对齐方式字
字符串.center(宽度,填充字符)
字符串.ljust(宽度,填充字符)
字符串.rjust(宽度,填充字符)
字符串.zfill(宽度)
str1 = "abc"
print(str1.center(7,"=")) # ==abc==
print(str1.ljust(7,"=")) # abc====
print(str1.rjust(7,"=")) # ====abc
# 20114507001 20114507002 20114507010 20114507015 20114507100
num = 15
study_id = "python1903" + str(num).zfill(3)
print(study_id) # python1903015
2)统计个数
字符串1.count(字符串2) - 统计字符串1中字符串2的个数
str2 = "how are you? fine,thank you! and you?"
print(str2.count("you")) # 3
print(str2.count("o")) # 4
3)
字符串.join(序列) - 将序列中的元素用指定的字符串连接在一起产生一个新的字符串
注意:序列的元素必须是字符串
print("*".join("abc")) # a*b*c
print(",".join(["余婷","张三","小明"])) # 余婷,张三,小明
4) 去掉空白字符
字符串.rstrip() - 去掉字符串右边的空白
字符串.lstrip() - 去掉字符串左边的空白
字符串.strip() - 去掉字符串左右两边的空白
str3 = " 数的 "
print("|"+str3+"|")
# str3 = str.lstrip() # |数 的 |
# str3 = str3.rstrip() # | 数 的|
str3 = str3.strip() # |数 的|
print("|"+str3+"|")
5)字符串替换
**字符串.replace(字符串1,字符串2) - 将字符串中的字符串1替换成字符串2
str4 = "how are you!and you!"
new_str = str4.replace("a","+")
print(new_str)
new_str = str4.replace("you","me")
print(new_str)
6)字符切割
**字符串.split(字符串1) - 将字符串按照字符串1进行切割,结果是包含多个小字符串的列表
str4 = "how are you! and you!"
print(str4.split(" ")) # ["how","are","you!", "and" ,"you!"]