字符串常规操作

字符串格式化的三种方式:

print('my name is %s'%name)

str1 = "I am {}, age {}".format("yusheng_liang", 20)

str1 =f"Hey {name}, there's a {errno} error!"

补充:转义r: r'转义 ', 二进制格式:b"二进制格式",s.encode()转化为二进制

print(r'转义
')   # r 表示把 
 等特殊字符转化为字符串输出
a = 'bigbox'
b = b'bigbox'
c = a.encode()
print(a,b,c)
print(type(a),type(b),type(c))

优先掌握知识点  

字符串 切片:  s1[1:3]     去空格  strip($)    切分 split('|')得到列表       连接 join(l)   得到字符串

 补充:isalpha  字母  isspace 空格isascii  isnumberic  islower isupper istitle   isdigit 是否是数字    replace   startwith

# 1.索引取值:正向取  反向取 (只能取,不能改)
s1 = 'hello world'
print(s1[6])
print(s1[-3])   #反向取从-1 开始
# 2.索引切片
print(s1[1:3])
print(s1[1:])
print(s1[:4])
print(s1[0:-2:2])  #按步长来切取
print(s1[1:9:-1])    #反向切片
# 3.成员运算符  in  not in
print('h' in s1)
#4.strip: 去除字符串左右两边的空格,中间的无法去除
name = input('>>:')
print(len(name))
nm = name.strip()
print(len(nm))
n1 = '$$$123$$'
print(n1.strip('$'))

# 5.split 切分:对字符串进行切分,可以指定切分符:为空格或某一字符,切分后返回的是一个列表
m1 = 'luxun/male/135'
print(m1.split('/'))
# 6. len()
print(len(m1))

需要掌握的知识点

# 1. strip, lstrip, rstrip  左空格,右空格
s = input('>>:')
print(s.lstrip('#'))
print(s.rstrip('#'))
# 2. lower/upper
print(s1.upper())
print(s1.lower())
# 3.startwith endwith
print(s1.startswith('he'))
print(s1.endswith('d'))
# split 可以指定切分的次数
s2 = "luxun, male, 135"
print(s2.split(',',1))
#jion 将列表中每个元素按照前面字符串中的分割符进行拼接   连接起来
s3 = "-"
l2 = ['luxun','male','135']
print(s3.join(l2))   # join 为字符串的方法,用字符去连接一组数据
#replace:将字符串中的元素进行替换,参数,先老值,再新值
print(s2.replace('135','200'))
#isdigit() 判断当前字符串中的数据,是否是一个数字,返回布尔值
s4='200'
print(s4.isdigit())

了解字符串操作

s1 = 'wtmm crazy'
# find # 查找当前字符串中某个元素的位置,返回索引,找不到返回-1
print(s1.find('a'))
# index  # 查找当前字符串中某个元素的位置,返回索引,找不到返回异常
print(s1.index('a'))
# count  # 统计当前字符串中某一个元素的个数
print(s1.count('m'))

#centerljust
justzfill

print("欢迎光临".center(8,"-"))

print("欢迎光临".ljust(30,"-"))
print("欢迎光临".rjust(30,"-"))

print("欢迎光临".zfill(50))
原文地址:https://www.cnblogs.com/bigbox/p/11800854.html