PythonStudy——字符串常用操作 String common operations
# 1.字符串的索引取值: 字符串[index]
# 正向取值从0编号,反向取值从-1编号
s1 = '123abc呵呵' print(id(s1)) # 2217572683576 print(s1[0], id(s1[0])) # 2217543167200 t_s = '1' print(id(t_s)) # 2217543167200
# 取出c
print(s1[5], s1[-3])
# 2.字符串拼接
s2 = '你好' s22 = '帅' ss2 = s2 + s22 print(ss2, id(s2), id(s22), id(ss2))
# 如果要拼接其他类型
a = 10 b = "20" c = True # res = "1020True" res = "%s%s%s" % (a, b, c) # 方法1 print(res) res = str(a) + b + str(c) # 方法2 print(res)
# 3.字符串长度
s3 = '12345' ln1 = s3.__len__() print(ln1) ln2 = len(s3) print(ln2)
# 4.字符串切片: 取子字符串 - [::] - [start_index:end_index:step]
s4 = '123abc呵呵' sub_s = s4[0:6:] print(sub_s) # 123abc sub_s = s4[0:6:2] print(sub_s) # 13b sub_s = s4[::-1] print(sub_s) # 呵呵cba321 sub_s = s4[-1:-6:-1] print(sub_s) # 呵呵cba
# 5.成员运算:判断某字符串是否在该字符串中
s5 = '123abc呵呵' ss5 = '12a' print(ss5 in s5) # False print(ss5 not in s5) # True
# 6.字符串循环(遍历)
s6 = '123abc呵呵' for v in s5: print(v)