> 文档中心 > 03 字符串操作

03 字符串操作


1、 计算UTF-8/GBK编码的字符串长度

str1 = '人生苦短,我用Python!'  # 定义字符串length = len(str1.encode())   #计算UTF-8编码的字符串的长度length1 = len(str1.encode('gbk'))     #计算GBK编码的字符串的长度print(length)print(length1)

2、分割字符串(split)

str1 = '人 生 苦 短 >>> 我 用 P y t h o n ! >>> csdn.com'print('原字符串:',str1)list1 = str1.split()      # 采用默认分隔符进行分割list2 = str1.split('>>>') # 采用多个字符进行分割list3 = str1.split('.')   # 采用.号进行分割list4 = str1.split(' ',4) # 采用空格进行分割,并且只分割前4个print(str(list1) + '\n' + str(list2) + '\n' + str(list3) + '\n' + str(list4))list5 = str1.split('>')   # 采用>进行分割print(list5)

3、格式化字符串%

# 定义模板template = '编号:%.4d\t公司名称: %s \t官网: http://www.%s.com'#定义要转换的内容context1 = (7,'百度','baidu')context2 = (8,'明日学院','mingrisoft')# 格式化输出print(template%context1)print(template%context2)

4、格式化字符串{:}

# 定义模板template = '编号:{:0>9s}\t公司名称: {:s} \t官网:/' \    ' http://www.{:s}.com'# 转换内容context1 = template.format('7','百度','baidu')context2 = template.format('10','明日学院','mingrisoft')# 输出格式化后的字符串print(context1)print(context2)