特性

定义多行字符串 ( 三引号 )

  1. str = """ 第一行
  2. 第二行
  3. 第三行"""

支持索引,(可迭代对象-可以被for循环遍历)

Python 还支持使用负索引(negative index)查找列表中的元素:可用来从右向左查找可迭代对象中元素的索引(必须是一个负数)。使用索引-1 可以查找可迭代对象中的最后一个元素,-2指倒数第二个;

字符串是不可变的

字符串和元组一样都是不可变的,无法修改字符串中的字符。如果想要修改,就必须创建一个新的字符串

字符串拼接 (+)

  1. str = "cat" + "in" + "hat"

字符串乘法

  1. "Sawyer" * 3
  2. >>> SawyerSawyerSawyer

字符转义

字符转义会将

方法

改变大小写

  • 大写(upper)

    1. "We hold these truths...".upper
  • 小写(lower)

    1. "SO IT GOES.".lower()

模板字符串-format

在花括号中添加自己想要的字符串,支持变量操作

  1. author = "William Faulkner"
  2. year_born = "1897"
  3. "{} was born in {}.".format(author, year_born)

简式写法

  1. for i , val in enumerate(lists):
  2. print("index= %s,val : %s"%(i,val))

split 可用来将字符串分割为两个或多个字符串 (返回一个列表)

  1. "I jumped over the puddle. It was 12 feet!".split(".")
  2. >> ["I jumped over the puddle", "It was 12 feet!"]

jion 在字符中添加字符(支持字符和列表操作)

  • 字符

    1. first_three = "abc"
    2. result = "+".join(first_three)
    3. >>> 'a+b+c'
  • 列表操作

    1. world = ["the","frist","name"]
    2. name = " ".join(world)
    3. >>> the frist name

去空格 (strip)

strip方法可以去除字符串开头和结尾的空格;

  1. s = " en "
  2. s = s.trip()
  3. >>> en

替换 replace

接受两个参数 第一个是要被替换的字符串; 第二个是替换的字符串; (会替换所有匹配的字符串)

  1. equ = "All animal is equal"
  2. equ.replace("a" , "@");
  3. >>> All @nim@l is equ@al

查找索引 index

返回某个字符第一次出现的索引;

  1. "animals".index("m")
  2. >>> 3

如果未找到则会报错;建议使用 try catch 包裹起啦
**

检测是否存在某个字符 in (前面可以添加 not)

  1. "Bat" in "Cat in the hat."
  2. >>> false
  3. "Bat" in "Cat in the hat."
  4. >>> true

切片

切片(slicing)可将一个可迭代对象中元素的子集,创建为一个新的可迭代对象。切片的语法是[可迭代对象][[起始索引:结束索引]]。起始索引(start index)是开始切片的索引,结束索引(end index)是结束索引的位置。
可迭代元素包括 : 列表 字符串 元祖 和 字典

  1. fict = ["Tony","Tome","joy"]
  2. fict[0,1]
  3. # 如果起始索引是 0,那么可以将起始索引的位置留空:
  4. fict[:1]
  5. #起始索引和结束索引均留空,则会返回原可迭代对象:
  6. fict[:]

**