基本数据类型(字符串)
1,创建字符串
st1 = 'victor' # 单引号创建 st2 = "victor" # 双引号创建 st3 = st("victor") # 1个参数,即普通创建字符串;2个参数,1个为字节,1个为编码 st4 = st() # 无参数,即创建空字符串(即空格)
2,基本操作
a,连接
st = "a" + "b" print st >>>ab
b,判断
print ("v" in "victor") >>>True
c,复制
print("victor"*4) >>>victor victor victor victor
d,索引
str = "abcdefghi" print (str[3], str[7]) >>>d h
e,切片
st = "abcdefghi" print (st[:2]) >>>ab
f,步长
st = "abcdefghi" print (st[::2]) >>> acegi
3,常用功能
a,替换
st = "abcdefg" print (st.replace("a", "A")) >>>Abcdefg
b,分割
st = "abcdefg" print (st.split("c")) >>>['ab', 'defg']
c,连接
lst = ["my", "name", "is", "victor"] st = " " # 用空格连接 print (st.join(lst)) >>>my name is victor"
d,判断以“str2”开头
st = 'abcdefghi' print (st.startswith('a')) >>>True
e,判断以“str2”结尾(str.endswith(str2))
st = 'abcdefghi' print (st.endswith('h')) >>>False
f,大小写
st = 'aBcDefgHi' print (st.upper()) # 全部大写 print (st.lower()) # 全部小写 print (st.swapcase()) # 大小写互换 print (st.capitalize()) # 首字母大写 >>>ABCDEFGHI abcdefghi AbCdEFGhI ABcDefgHi
d,删除字符末尾空格
st = 'abcdefghi ' print (st.rstrip()) >>>abcdefghi
4,转义字符(\)
print ('\'', '\"') >>>' " print ('my name \n is vitcor') # '\n'为空行 >>>my name is victor print ('\\') >>>\ # 文件路径用‘/’,或者‘\\’
5,格式化
a,百分号:%
name = "dian dian" sun = "my son is %s" %name # 前一个%代表插入的数据类型,后一个%代表插入变量名 print (sun) >>>my son is dian dian
b,format()
sun = "my son is {}".format("dian dian") # {}和{0}都是占位符,{0}更加明确指定为占位符 print (sun) >>>my son is dian dian print ("my son is {name}".format(name = "dian dian")) # 可以用变量来指示 >>>my son is dian dian st = "my son is {}" st = st.format("dian dian ") # 生成新的值 print st >>>my son is dian dian