字符串是Python中最常用的数据类型(字符串是字符的序列)
我们可以使用引号( ' 或 " )来创建字符串
- txt1 = 'Hello World!!'
- print(txt1) # Hello World!!
- txt2 = "Hello World!!"
- print(txt2) # Hello World!!
- str1 = 'What\'s your name?'
- str2 = "What's your name?"
- print(str1) # What's your name?
- print(str2) # What's your name?
补充:字符串合并可使用+运算符
- str1 = 'Hello'
- str2 = 'World'
- print(str1 + str2) # HelloWorld
- print(str1 + ' ' + str2) # Hello World
字符串中的所有元素都是有编号的,即我们所说的索引值,从0开始递增
我们可以使用索引来获取字符
- txt = 'ABCDEFGHIJKLMN'
- print(txt[0]) # A
- print(txt[2]) # C
- print(txt[-2]) # M
- print(txt[-1]) # N
除了使用索引访问单个字符外,我们还可以使用切片(slicing)来访问特定范围内的字符
- tag = 'Hudas Blog'
- tag[9:36] # 'https://blog.csdn.net/Hudas'
- tag[38:-4] # 'Hudas Blog'
扩展补充知识
Python切片操作https://blog.csdn.net/Hudas/article/details/125905111
len(str)可用于获取字符串长度
注明:str代表字符串
- txt = 'I love Python very much!!'
- print(len(txt)) # 25
- exp_str = "Hello World!!"
- result = exp_str.startswith("Hello")
- print(result) # True
- txt = "China is a great country"
- result = txt.endswith("country")
- # True
- print(result)
upper()用于返回字符串的大写版本
lower()用于返回字符串的小写版本
capitalize()与title()用于将字符串转换为词首大写(首字母大写)
- txt = "hello world!!"
- # 把所有字符中的小写字母转换成大写字母
- print(txt.upper()) # HELLO WORLD!!
- # 把所有字符中的大写字母转换成小写字母
- print(txt.lower()) # hello world!!
- # 把第一个字母转化为大写字母,其余小写
- print(txt.capitalize()) # Hello world!!
- # 把每个单词的第一个字母转化为大写,其余小写
- print(txt.title()) # Hello World!!
-
- txt1 = "blog.csdn.net"
- # BLOG.CSDN.NET
- print(txt1.upper())
- # blog.csdn.net
- print(txt1.lower())
- # Blog.csdn.net
- print(txt1.capitalize())
- # Blog.Csdn.Net
- print(txt1.title())
index()方法与find()方法功能一样,用于查询指定检索的字符串是否包含在目标字符串内,如果包含在内,返回第一个指定检索字符串在目标字符串起始索引值
如果指定检索的字符串不在目标字符串内,index()方法会报异常,find()方法返回-1
- str1 = 'Python'
- str1.find('t') # 2
- str1.index('t') # 2
- str1.find('hon') # 3
- str1.index('hon') # 3
- str1.find('z') # -1
- str1.index('z') # ValueError: substring not found
扩展补充知识
index()方法 VS find()方法https://blog.csdn.net/Hudas/article/details/122873780
replace()可以将指定子字符串替换为另一个字符串,并返回替换后的结果
- txt = 'This is a test'
- # This is a demo
- print(txt.replace('test','demo'))
替换字符串中的多个子字符
- sentence = "The lazy brown fox jumps over the lazy dog"
-
- for words in (("brown", "red"), ("lazy", "quick")):
- sentence = sentence.replace(*words)
- # The quick red fox jumps over the quick dog
- print(sentence)
strip()可以将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果
lstrip()去除字符串左边空格
rstrip()去除字符串右边空格
- txt = " Andy437 "
- # 去除首尾空格
- print(txt.strip()) #Andy437
- # 去除左边空格
- print(txt.lstrip()) #Andy437
- # 去除右边空格
- print(txt.rstrip()) # Andy437
补充扩展知识
strip()方法https://blog.csdn.net/Hudas/article/details/122849506
split()用于将字符串拆分为序列
注意:如果没有指定分隔符,将默认在单个或多个连续的空白符(空格、制表符、换行符等)处进行拆分
- txt = '1+2+3+4+5'
- # ['1', '2', '3', '4', '5']
- print(txt.split('+'))
-
- txt1 = '/usr/bin/env'
- # ['', 'usr', 'bin', 'env']
- print(txt1.split('/'))
-
- txt2 = 'Using the default'
- # ['Using', 'the', 'default']
- print(txt2.split())
补充扩展知识
split()方法https://blog.csdn.net/Hudas/article/details/122849811
join()用于合并序列的元素,其作用与split相反
注意:所合并序列的元素必须都是字符串
- nums = [1, 2, 3, 4, 5]
- s = '+'
- # 报错,TypeError: sequence item 0: expected str instance, int found
- print(s.join(nums))
- nums = ['1', '2', '3', '4', '5']
- s = '+'
- # '1+2+3+4+5'
- print(s.join(nums))
扩展补充知识
join()方法https://blog.csdn.net/Hudas/article/details/122850092
count()用于统计字符串里某个字符或子字符串出现的次数
- # 检查字符'a'在sentence中出现的次数
- sentence = 'Canada is located in the northern part of North America'
- counter = sentence.count('a')
- print(counter) # 6
我们也可以使用一下方法实现上述count()的效果
- # 检查字符'a'在sentence中出现的次数
- sentence = 'Canada is located in the northern part of North America'
- # 方法1
- import re
- counter = len(re.findall("a", sentence))
- print(counter) # 6
-
- # 方法2
- from collections import Counter
- counter = Counter(sentence)
- print(counter['a']) # 6
扩展补充知识
count()方法https://blog.csdn.net/Hudas/article/details/122941544
格式化字符串函数str.format()
- # 下面输出结果都为"My name is Andy, I'am 18"
- txt1 = "My name is {fname}, I'am {age}".format(fname = "Andy", age = 18)
- txt2 = "My name is {0}, I'am {1}".format("Andy",18)
- txt3 = "My name is {}, I'am {}".format("Andy",18)
扩展补充知识
format格式化函数https://blog.csdn.net/Hudas/article/details/122849967
isalpha()用于检测字符串是否只由字母组成,如果字符串中所有字符都是字母则返回True,否则返回False
- txt1 = "python"
- print(txt1.isalpha()) #True
-
- # 中文的汉字会被isalpha判定为True
- txt2 = "这是一个例子"
- print(txt2.isalpha()) # True
- # 如果想区分中文和英文,可以使用如下方法
- print(txt2.encode("utf-8").isalpha()) # False
-
- txt3 = "Andy安迪"
- print(txt3.isalpha()) # True
- print(txt3.encode("utf-8").isalpha()) # False
isdigit()用于检测字符串是否只由数字组成,结果返回True或False
注意:只对0和正数有效
- str1 = '123456'
- print(str1.isdigit()) # True
-
- str2 = "Hello Wrold!!"
- print(str2.isdigit()) # False
-
- str3 = '0'
- print(str3.isdigit()) # True
-
- str4 = '-1'
- print(str4.isdigit()) # False
-
- str5 = '1.437'
- print(str5.isdigit()) # False
-
- str6 = '12.0'
- print(str6.isdigit()) # False
isalnum()用于检测字符串是否由字母和数字组成,结果返回True或False
- str1 = "year2022"
- print(str1.isalnum()) # True
-
- str2 = "HelloWorld"
- print(str2.isalnum()) # True
-
- str3 = "Hello World"
- print(str3.isalnum()) # False
-
- str4 = "437"
- print(str4.isalnum()) # True
islower()用于检测字符串中所有的字母是否都为小写,结果返回True或False
- txt1 = "HELLO world!!!"
- print(txt1.islower()) # False
- txt2 = "hello world!!!"
- print(txt2.islower()) # True
- txt3 = '437'
- print(txt3.islower()) # False
- txt4 = 'andy437'
- print(txt4.islower()) # True
- txt5 = 'Andy437'
- print(txt5.islower()) # False
isupper()用于检测字符串中所有的字母是否都为大写,结果返回True或False
- txt1 = "HELLO WORLD!!!"
- print(txt1.isupper()) # True
- txt2 = "HELLO world!!!"
- print(txt2.isupper()) # False
- txt3 = '437'
- print(txt3.isupper()) # False
- txt4 = 'andy437'
- print(txt4.isupper()) # False
- txt5 = 'Andy437'
- print(txt5.isupper()) # False
- txt6 = 'ANDY437'
- print(txt6.isupper()) # True
istitle()用于检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写,结果返回True或False
- txt = 'Andy'
- print(txt.istitle()) # True
- txt1 = 'Aa Bc'
- print(txt1.istitle()) # True
- txt2 = 'Aa_Bc'
- print(txt2.istitle()) # True
- txt3 = 'Aa bc'
- print(txt3.istitle()) # False
- txt4 = 'Aa_bc'
- print(txt4.istitle()) # False
- txt5 = 'Aa BC'
- print(txt5.istitle()) # False
- txt6 = '437'
- print(txt6.istitle()) # False
- txt7 = 'A437'
- print(txt7.istitle()) # True
- txt8 = 'helloWorld'
- print(txt8.istitle()) # False
isspace()用于检测字符串是否只由空格组成,结果返回True或False
- txt1 = " "
- print(txt1.isspace()) # True
- txt2 = "Test"
- print(txt2.isspace()) # False
- txt3 = " Test "
- print(txt3.isspace()) # False
- txt4 = ' \t'
- print(txt4.isspace()) # True
- txt5 = '\n'
- print(txt5.isspace()) # True
- txt6 = 'Aa Bb'
- print(txt6.isspace()) # False
注意
- txt = ''
- print(txt.isspace()) # False
扩展补充判断字符串是否为空的其他方法
- username1 = ""
-
- # 方法1:使用字符串长度判断
- if len(username1) == 0:
- print("用户名不能为空")
-
- # 方法2:使用==判断是否为空
- if username1 == '':
- print("用户名不能为空")
-
- # 方法3:直接判断是否为空
- if username1:
- print("Welcome!!")
- else:
- print("用户名不能为空")
-
- username2 = " "
- # 使用.isspace()判断是否字符串全部是空格
- if username2.isspace() == True:
- print("用户名不能为空")