1. 含义及其表选形式
字符串就是一系列字符,在Python当中用引号括起来的都是字符串,其中引号可以是单引号‘…’,双引号“…”,三引号“””…””” or ‘’’…’’’(支持换行);例如:a = 'this is string'
b = "this is also a string"
c = '''this is string'''
2. 使用方式
2.1. 使用方法修改字符串的大小写
a = 'this IS String'
print(a.title()) # 输出结果为This Is String
'''title()函数是以首字母为大写显示每个单词'''
print(a.upper()) #输出结果为THIS IS STRING
'''upper()函数是把字符串单词全部更改为大写'''
print(a.lower()) #输出结果为this is string
'''lower()函数把字符串单词全部更改为小写'''
2.2. 合并(拼接)字符串,字符串与字符串之间使用”+”拼接
a = "hello"
b = " china"
print(a+b)#输出结果为hello china
2.3. 索引,切片
a = 'this IS String'
print(a[0])#输出结果为t,索引第一个字符为0
print(a[0:3])#输入结果为‘thi’,不包含‘3’对于的字符
print(a[3:9])#输出结果为‘s IS’,'3'对于字符包含,‘9’对于字符不包含
print(a[-1])#从右边开始
2.4. 字符串转义字符 “\” 用法
\n:标志换行
print('this\nis\nstring')
'''
输入结果为:
this
is
string
'''
\t:表示tab键缩进
print('this\tis\tstring')
'''
输入结果为:this is string
'''
2.5. 字符串不需要转义的方法:路径中”\” or “r” 用法,如果不需要”\”,则使用”\“
print('D:\Yuque\yuque-desktop\tlocales')#输入结果为D:\Yuque\yuque-desktop locales,"\"和"t"合起来变成了缩进功能
print('D:\Yuque\yuque-desktop\\tlocales')#输出结果为D:\Yuque\yuque-desktop\tlocales,使用"\\"就能正常显示了
'''在字符串前面添加r也能达到同样的效果'''
print(r'D:\Yuque\yuque-desktop\tlocales')#输出结果为D:\Yuque\yuque-desktop\tlocales
2.6. 步长
切片的取值顺序永远都是从左往右顺序取值。不能从右往左取值。
步长可以指定取值顺序:基本语法如下:
print(a[start:end:step])
start:起始位置;end:结束位置;step:取值顺序,取值间隔(step为正:从左往右取值,反之从右往左)