字符串及字符串的常用方法
str(不可变数据类型)
字符串的定义(不区分单引号和双引号)
str1 = "HelloWorld"
str2 = 'HelloWorld'
字符串的输入
str = input("从键盘任意录入一个字符串:")
字符串求长度
长度 = len(变量/常量)
字符串的索引值
范围:[0,len(变量)-1]
# 使用循环完成字符串中每个字符串的打印,使用\t隔开 str = "Hello" # 1.while循环 i = 0 length = len(str) print("使用while循环进行字符串打印:") while i < length: print(str[i],end="\t") i += 1 # 2.for循环 print("\n第一种使用for循环进行字符串打印:") for i in range(length): print(str[i], end="\t") print("\n第二种使用for循环进行字符串打印:") for i in str: print(i, end="\t")
操作字符串常用的方法
1.字符串的切片操作
字符串变量名[start:end:step]
不包含end
注意:切片操作不会报越界异常 IndexError
str_num = "0123456789" # 从开始位置截取两个字符出来 result = str_num[0:2] print("从字符串\"{0}\"开始位置截取两个字符出来:{1}".format(str_num,result)) # 从开始位置为1的地方,截取八个字符出来,并设置步长为2 result2 = str_num[1:9:2] print("从字符串\"{0}\"开始位置为1的地方,截取八个字符出来,并设置步长为2:{1}".format(str_num,result2)) # step为负值,表示从右往左取(如果要指定开头和结尾,开头的值要大,结尾的值要小) result3 = str_num[::-1] print("将字符串\"{0}\"倒序输出:{1}".format(str_num,result3))
2.find/rfind
如果有返回索引值,没有则返回-1
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" # find从左往右找 print(str2.find("no")) # rfind从右往左找 print(str2.rfind("no"))
3.index/rindex
跟find()方法一样,如果有返回索引值,只不过没有找到的话会报一个异常 raise ValueError
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" # 索引值index跟find类似,从左往右寻找索引值 print(str2.index("no")) # # 跟find类似,从右往左找索引值 print(str2.rindex("no"))
4.count
返回str在目标字符串中start-end之间出现的次数,如果有返回出现的次数,没有则返回0
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" # count统计字符串出现的次数 print(str2.count("no"))
5.replace
修改字符串中的指定字符
(注意:replace不是对原字符串str2进行替换,而是将替换完之后的值存储到新的地方)
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" str3 = str2.replace("you","YOU") # 注意:replace不是对原字符串str2进行替换,而是将替换完之后的值存储到新的地方 print("id:{0}\tstr2 = {1}".format(id(str2),str2)) print("id:{0}\tstr3 = {1}".format(id(str3),str3)) # 只对第一个can进行替换 str3_1 = str2.replace("can","CAN",1) print("id:{0}\tstr3_1 = {1}".format(id(str3_1),str3_1))
6.split
以指定分隔符,对字符串进行拆分(拆分好的字符串,以list类型进行存储)
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" # split以指定分隔符空格,对字符串进行拆分,并且将拆分好的字符串,以list类型进行存储 str4 = str2.split(" ") print("str4 的数据类型:",type(str4)) print("str4 = ",str4)
7.capitalize
把字符串的第一个字符大写
str1 = "good good study,day day up" str2 = "you can you up,no can no b b" # capitalize将字符串首字母大写 str5 = str2.capitalize() print("str5 = ",str5)
8.titile
将所有单词的首字母大写
str = "you can you up,no can no b b" # title将所有单词的首字母大写 str1 = str.title() print("str1 = ",str1)
9.upper 和 lower
upper
转换字符串中的所有的小写字符为大写
lower
转换字符串中所有的大写字符为小写
str = "you can you up,no can no b b" # upper()小写字符转化为大写 str2 = str.upper() print("将所有小写字符转化为大写\tstr2 = ",str2) # lower()大写字符转化为小写 str3 = str2.lower() print("将所有大写字符转化为小写\tstr3 = ",str3)
10.startswith 和 endswith
stratswith
判断字符串以什么开头,返回值为bool值
endswith
判断单词以什么结尾,返回值为bool值
# startswith()判断字符串以什么开头,返回值为bool值 url1 = "https://www.baidu.com/" # 判断字符串是否以"https://www"开头 if url1.startswith("https://www"): print("{}\t该网址为有效网址!".format(url1)) else: print("{}\t该网址为无效网址,请重新输入...".format(url1)) # endswith()判断字符串以什么结尾,返回值为bool值 fileName = "Test.py" # 判断字符串是否以".py结尾 if fileName.endswith(".py"): print("{}\t该文件为python文件!".format(fileName)) else: print("{}\t该文件不是python文件...".format(fileName))
11.isalpha 、 isdigit 和 isalnum
isalpha
判断目标字符串中是否所有的字符都为字母,返回True,或者False
isdigit
判断目标字符串中是否所有的字符都为数字,返回True,或者False
isalnum
判断目标字符串是否所有的字符都为字母和数字组合,返回True,或者False
num_input = input("请输入一个字符串:") if num_input.isalpha(): print("该字符串都为字母组合...") elif num_input.isdigit(): print("该字符串都为数字组合...") elif num_input.isalnum(): print("该字符串为字母和数字组合...") else: print("该字符串为其他组合...")
12.ljust(),rjust(),center()
字符串对齐,剩下的以"指定字符"填充
(不写则默认以空格进行填充)
str1 = "马铃薯" print(str1) # ljust字符串居左对齐,剩下的以"*"填充 print("字符串居左对齐:",str1.ljust(10,"*")) # rjust字符串居右对齐,剩下的以"*"填充 print("字符串居右对齐:",str1.rjust(10,"*")) # center字符串居中对齐,剩下的以"*"填充 print("字符串居中对齐:",str1.center(10,"*"))
13.lstrip(),rstrip(),strip()
用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
str1 = " tyy " print(str1) print("删除字符串左边的空格:",str1.lstrip()) print("删除字符串右边的空格:",str1.rstrip()) print("删除字符串两边的空格:",str1.strip())