一、定义

在单引号\双引号\三引号内包含一串字符
name1 = 'jason' 		 # 本质:name = str('任意形式内容')
name2 = "lili"  		 # 本质:name = str("任意形式内容")
name3 = """ricky"""  	 # 本质:name = str("""任意形式内容""")

1、类型转换

数据类型转换:str()可以将任意数据类型转换成字符串类型,例如 
print(str(19))
print(str(19.1))
print(str([1, 2, 3, 4]))
print(str({'username':'kecin', 'age':18}))
print(str((1,2,3,4)))
print(str(True))
print(str({11,22,33}))

2、按索引取值(正向取,反向取):

正向取(从左往右)
>>> str1[6]
p
反向取(负号表示从右往左)
>>> str1[-4]
h
对于str来说,只能按照索引取值,不能改
>>> str1[0]='H' # 报错TypeError

3、切片(顾头不顾尾,步长)
顾头不顾尾:取出索引为0到8的所有字符

>>> str1[0:9]  
hello pyt

步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符

>>> str1[0:9:2]  
hlopt
字符串的负数切片,工作中能不用就不用

反向切片

>>> str1[::-1]  # -1表示从右往左依次取值
!nohtyp olleh

4、长度“len()”
获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符

>>> len(str1) # 空格也算字符
13

5、"strip()"括号里什么都不写,移除字符串首尾指定的字符(默认移除空格)(可以认为是居中)
括号内不指定字符,默认移除首尾空白字符(空格、\n、\t)

>>> str1 = '**tony***'

>>> str1.strip('*')  # 移除左右两边的指定字符
'tony'
>>> str1.lstrip('*')  # 只移除左边的指定字符
tony***
>>> str1.rstrip('*')  # 只移除右边的指定字符
**tony
括号内指定字符,移除首尾指定的字符
>>> str2 = '**tony**'  
>>> str2.strip('*')  
tony

6、切分“split()”

括号内不指定字符,默认以空格作为切分符号
>>> str3='hello world'
>>> str3.split()
['hello', 'world']
source_data = 'kevin|123|xx1'
# s1, s2,s3 = source_data.split("|")#左右为索引取值
print(s3)#xx1
括号内指定分隔字符,则按照括号内指定的字符切割字符串
>>> str4 = '127.0.0.1'
>>> str4.split('.')  
['127', '0', '0', '1']  # 注意:split切割得到的结果是列表数据类型

7、lower(), upper()字符串转大小写

>>> str2 = 'My nAme is tonY!'

>>> str2.lower()  # 将英文字符串全部变小写
my name is tony!
>>> str2.upper()  # 将英文字符串全部变大写
MY NAME IS TONY!
图片验证码不区分大小写
思路:把用户输入的验证码全部转为大写或者小写,跟原来的验证码都转为大写或者小写进行比较
# old_code = 'oldBoY'
# print('返回给你的验证码是:%s' % old_code)
# # 用户输入的验证码
# real_code=input('请输入验证码:')
# # if old_code.lower() == real_code.lower():
# if old_code.upper() == real_code.upper():
#     print('验证码输入正确')
# else:
#     print('验证码错误')
判断是否是小写或者是大写.islower(),.isupper()
# 补充:
print(res.islower())  # False
print(res.isupper())  # False

a ='hello'
print(a.islower())  # True


res = 'Kevin123 OldGirl'
print(res.startswith('K'))  # True
print(res.startswith('kev'))  # True
print(res.startswith('Keva'))  # True

print(res.endswith('Girl'))
print(res.endswith('rl'))

8、startswith(), endswith()判断字符串是否以括号内指定的字符开头或者结尾,结果为布尔值True或False

>>> str3 = 'tony jam'

# startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
>>> str3.startswith('t') 
True
>>> str3.startswith('j')
False
# endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
>>> str3.endswith('jam')
True
>>> str3.endswith('tony')  
False

9、格式化输出之format()
之前我们使用%s来做字符串的格式化输出操作,在传值时,必须严格按照位置与%s占位然后用%(值)一一对应,而字符串的内置方法format则提供了一种不依赖位置的传值方式
format的三种使用方式

第一种玩法(用{}进行占位)类似于%s的用法,传入的值会按照位置与{}一一对应
s = 'my name is %s, my age is %s' % ('kevin', 18)
s = 'my name is {}, my age is {}'
print(s.format('kevin', 20)) 
run:my name is kevin, my age is 20​
>>> str4 = 'my name is {}, my age is {}!'.format('tony', 18)
>>> str4 
my name is tony, my age is 18!
'''第二种玩法'''把format传入的多个值当作一个列表,然后用{索引}取值
>>> str4 = 'my name is {0}, my age is {1}!'.format('tony', 18)
>>> str4
my name is tony, my age is 18!

>>> str4 = 'my name is {1}, my age is {0}!'.format('tony', 18)
>>> str4  
my name is 18, my age is tony!

>>> str4 = 'my name is {1}, my age is {1}!'.format('tony', 18)
>>> str4  
my name is 18, my age is 18!

'''第三种玩法'''(将{}里填入相应的值,然后在用pofmat给{}离面的值赋予值,类似键值对)
s = '{age}my name is {name}, my age is {age}
print(s.format(name='kevin', age=20))

10、拼接字符串,join()

# 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
>>> '%'.join('hello') 				# 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接
'h%e%l%l%o'
>>> '|'.join(['tony','18','read'])  # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接
'tony|18|read'

11、replace()替换字符串

# 用新的字符替换字符串中旧的字符
>>> str7 = 'my name is tony, my age is 18!'  # 将tony的年龄由18岁改成73岁
>>> str7 = str7.replace('18', '73') 		 # 语法:replace('旧内容', '新内容')
>>> str7
my name is tony, my age is 73!

# 可以指定修改的个数
>>> str7 = 'my name is tony, my age is 18!'
>>> str7 = str7.replace('my', 'MY',1) 		 # 只把一个my改为MY
>>> str7
'MY name is tony, my age is 18!'

12、isdigit()判断字符串是否是纯数字组成,返回结果为True或False

>>> str8 = '5201314'
>>> str8.isdigit()
True

>>> str8 = '123g123'
>>> str8.isdigit()
False

了解内容不常用

find,rfind,index,rindex,count
# 1.1 find:从指定范围内查找子字符串的起始索引,找得到则返回数字1,找不到则返回-1
>>> msg='tony say hello'
>>> msg.find('o',1,3)  # 在索引为1和2(顾头不顾尾)的字符中查找字符o的索引
1  
# 1.2 index:同find,但在找不到时会报错
>>> msg.index('e',2,4) # 报错ValueError
# 1.3 rfind与rindex:略
# 1.4 count:统计字符串在大字符串中出现的次数
>>> msg = "hello everyone"
>>> msg.count('e')  # 统计字符串e出现的次数
4
>>> msg.count('e',1,6)  # 字符串e在索引1~5范围内出现的次数
1


# 2.center,ljust,rjust,zfill
>>> name='tony'
>>> name.center(30,'-')  # 总宽度为30,字符串居中显示,不够用-填充
-------------tony-------------
>>> name.ljust(30,'*')  # 总宽度为30,字符串左对齐显示,不够用*填充
tony**************************
>>> name.rjust(30,'*')  # 总宽度为30,字符串右对齐显示,不够用*填充
**************************tony
>>> name.zfill(50)  # 总宽度为50,字符串右对齐显示,不够用0填充
0000000000000000000000000000000000000000000000tony


# 3.expandtabs
>>> name = 'tony\thello'  # \t表示制表符(tab键)
>>> name
tony    hello
>>> name.expandtabs(1)  # 修改\t制表符代表的空格数
tony hello


# 4.captalize,swapcase,title
# 4.1 captalize:首字母大写
>>> message = 'hello everyone nice to meet you!'
>>> message.capitalize()
Hello everyone nice to meet you!  
# 4.2 swapcase:大小写翻转
>>> message1 = 'Hi girl, I want make friends with you!'
>>> message1.swapcase()  
hI GIRL, i WANT MAKE FRIENDS WITH YOU!  
#4.3 title:每个单词的首字母大写
>>> msg = 'dear my friend i miss you very much'
>>> msg.title()
Dear My Friend I Miss You Very Much 


# 5.is数字系列
#在python3中
num1 = b'4' #bytes
num2 = u'4' #unicode,python3中无需加u就是unicode
num3 = '四' #中文数字
num4 = 'Ⅳ' #罗马数字


#isdigt:bytes,unicode
>>> num1.isdigit()
True
>>> num2.isdigit()
True
>>> num3.isdigit()
False
>>> num4.isdigit() 
False

#isdecimal:uncicode(bytes类型无isdecimal方法)
>>> num2.isdecimal() 
True
>>> num3.isdecimal() 
False
>>> num4.isdecimal() 
False

#isnumberic:unicode,中文数字,罗马数字(bytes类型无isnumberic方法)
>>> num2.isnumeric() 
True
>>> num3.isnumeric() 
True
>>> num4.isnumeric() 
True

# 三者不能判断浮点数
>>> num5 = '4.3'
>>> num5.isdigit()
False
>>> num5.isdecimal()
False
>>> num5.isnumeric()
False

'''
总结:
	最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
	如果要判断中文数字或罗马数字,则需要用到isnumeric。
'''


# 6.is其他
>>> name = 'tony123'
>>> name.isalnum() #字符串中既可以包含数字也可以包含字母
True
>>> name.isalpha() #字符串中只包含字母
False
>>> name.isidentifier()
True
>>> name.islower()  # 字符串是否是纯小写
True
>>> name.isupper()  # 字符串是否是纯大写
False
>>> name.isspace()  # 字符串是否全是空格
False
>>> name.istitle()  # 字符串中的单词首字母是否都是大写
False