python之字符串的索引,切片,分割,替换,去除指定字符,拼接,格式化

# 字符串中的元素:单个字母,数字,汉字。单个字符都称为元素。

s = 'hello!'

1.len(数据):统计数据的长度

print(len(s))  # 6

2.字符串取值:字符串名[索引值]

# 正向索引:0,1,2……从0开始
# 反向索引:……-6,-5,-4,-3,-2,-1

print(s[5])  # 索引,!
print(s[-1])  # !

# 字符串取多个值:切片 字符串名[索引头:索引尾:步长]步长默认为1

print(s[1:5:2])   # el      # 取头不取尾1,3
print(s[1:5])  # ello      # 1,2,3,4
print(s[2:4:2])  # l     # 2
print(s[:])  # hello!     # 取全部
print(s[:4])  # hell     # 取3之前的全部0,1,2,3
print(s[3:])  # lo!     # 3以后的全取 3,4,5
print(s[-1:-7:-1])  # 倒序输出:!olleh
print(s[::-1])  # 倒序输出:!olleh

3.字符串分割 字符串.split('可以指定切割符号',指定切割次数)---只有字符串可以使用,返回一个列表类型的数据,列表中的子元素都是字符串类型

print(s.split('e'))  # ['h', 'llo!']
print(s.split('l'))  # ['he', '', 'o!']
print(s.split('l', 1))  # ['he', 'lo!']

4.字符串的替换 字符串.replace('可以指定替换值','新值',指定替换次数)

s1 = 'heelo!'
new = s1.replace('o', '@')
print(new)  # heel@!
new1 = s1.replace('e', '1', 2)
print(new1)  # h11lo!

 5.字符串的去除指定字符 字符串.strip('指定去除字符',指定替换次数)

# 只去掉头和尾的字符,不能去除直接字符

s = ' hello '
new3 = s.strip()    # 默认去空格
print(new3)   # hello
new4 = s.strip(' he')
print(new4)  # llo

 6.字符串的拼接+ 保证+左右两边的变量值的类型一致

s_1 = 'python,'
s_2 = 'welcome!'
s_3 = 666
print(s_1 + s_2 + str(s_3 ))  # s_3强制转换后才能拼接  # python,welcome!666
print(s_1, s_2, s_3)  # python, welcome! 666

7.字符串格式化输出 % format

age = 18
name = 'zhengzi'
print("欢迎进入" + str(age) + "岁的" + name + "的博客园")  # 欢迎进入18岁的zhengzi的博客园
# (1)格式化输出1:format 用{}来占位
print("欢迎进入{}岁的{}的博客园".format(age, name))  # 欢迎进入18岁的zhengzi的博客园,默认顺序
print("欢迎进入{1}博客园,她今年{0}".format(age, name))  # 欢迎进入zhengzi博客园,她今年18
# (2)格式化输出2:% %s字符串(任何数据), %d数字(整型)  %f浮点数 (%.2f四舍五入保留两位小数)
print("欢迎进入%d岁的%s的博客园" % (age, name))  # 欢迎进入18岁的zhengzi的博客园

猜你喜欢

转载自www.cnblogs.com/kite123/p/11628670.html