1. 含义及其表选形式

字符串就是一系列字符,在Python当中用引号括起来的都是字符串,其中引号可以是单引号‘…’,双引号“…”,三引号“””…””” or ‘’’…’’’(支持换行);例如:
a = 'this is string'
b = "this is also a string"
c = '''this is string'''

2. 使用方式

2.1. 使用方法修改字符串的大小写

  1. a = 'this IS String'
  2. print(a.title()) # 输出结果为This Is String
  3. '''title()函数是以首字母为大写显示每个单词'''
  4. print(a.upper()) #输出结果为THIS IS STRING
  5. '''upper()函数是把字符串单词全部更改为大写'''
  6. print(a.lower()) #输出结果为this is string
  7. '''lower()函数把字符串单词全部更改为小写'''

2.2. 合并(拼接)字符串,字符串与字符串之间使用”+”拼接

  1. a = "hello"
  2. b = " china"
  3. print(a+b)#输出结果为hello china

2.3. 索引,切片

  1. a = 'this IS String'
  2. print(a[0])#输出结果为t,索引第一个字符为0
  3. print(a[0:3])#输入结果为‘thi’,不包含‘3’对于的字符
  4. print(a[3:9])#输出结果为‘s IS’,'3'对于字符包含,‘9’对于字符不包含
  5. print(a[-1])#从右边开始

2.4. 字符串转义字符 “\” 用法

  • \n:标志换行

    1. print('this\nis\nstring')
    2. '''
    3. 输入结果为:
    4. this
    5. is
    6. string
    7. '''
  • \t:表示tab键缩进

    1. print('this\tis\tstring')
    2. '''
    3. 输入结果为:this is string
    4. '''

    2.5. 字符串不需要转义的方法:路径中”\” or “r” 用法,如果不需要”\”,则使用”\“

    1. print('D:\Yuque\yuque-desktop\tlocales')#输入结果为D:\Yuque\yuque-desktop locales,"\"和"t"合起来变成了缩进功能
    2. print('D:\Yuque\yuque-desktop\\tlocales')#输出结果为D:\Yuque\yuque-desktop\tlocales,使用"\\"就能正常显示了
    3. '''在字符串前面添加r也能达到同样的效果'''
    4. print(r'D:\Yuque\yuque-desktop\tlocales')#输出结果为D:\Yuque\yuque-desktop\tlocales

    2.6. 步长

    切片的取值顺序永远都是从左往右顺序取值。不能从右往左取值。
    步长可以指定取值顺序:

  • 基本语法如下:

print(a[start:end:step])
start:起始位置;end:结束位置;step:取值顺序,取值间隔(step为正:从左往右取值,反之从右往左)

总结:

python_str - 图1