[Python3] 011 字符串:给你们看看我的内置方法 第三弹

目录


少废话,上例子

1. encode(encoding='utf-8', errors='strict')

  • 释义:
    1. 使用 encoding 指定的编码格式对字符串进行编码,默认为 utf-8,不区分大小写
    2. errors 用于设置不同错误的处理方案,默认为 'strict',意为编码错误引起一个UnicodeError
    3. errors 其他可能的值有:'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值
    4. 直接看例子吧
  • 示例
# 例1

str1 = "YorkFish不是鱼"
str_utf8 = str1.encode("UTF-8")
str_gbk = str1.encode("GBK")
 
print("编码前: ", str1, end="\n\n")    # 设置 print 结尾为两个回车,方便阅读
 
print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk, end="\n\n")
 
print("utf-8 默认解码:", str_utf8.decode())     # 默认 encoding='utf-8',errors='strict'
print("utf-8 解码:", str_utf8.decode('utf-8','strict'))   # utf-8 不区分大小写
print("UTF-8 解码:", str_utf8.decode('UTF-8','strict'))
print("GBK 解码:", str_gbk.decode('GBK','strict'))        # gbk 也不区分大小写
  • 运行结果

编码前: YorkFish不是鱼

UTF-8 编码: b'YorkFish\xe4\xb8\x8d\xe6\x98\xaf\xe9\xb1\xbc'

GBK 编码: b'YorkFish\xb2\xbb\xca\xc7\xd3\xe3'

utf-8 默认解码: YorkFish不是鱼

utf-8 解码: YorkFish不是鱼

UTF-8 解码: YorkFish不是鱼

GBK 解码: YorkFish不是鱼

  • 不直观?来张截图:

2. expandtabs([tabsize=8])

  • 释义:
    1. 将字符串中的 Tab 符号,即 \t,转换为空格
    2. 如果不指定参数,默认空格数是 8
  • 示例
# 例2

str2 = "制表符攻击:\t!!!"

print ("替换 \\t 符号前: " + str2)
print ("替换 \\t 符号后: " +  str2.expandtabs())
print ("用 16 个空格替换 \\t 符号: " +  str2.expandtabs(16))
  • 运行结果

替换 \t 符号前: 制表符攻击: !!!

替换 \t 符号后: 制表符攻击: !!!

用 16 个空格替换 \t 符号: 制表符攻击: !!!

  • 不直观?来张截图:

借此机会简单地说一说 print()

  • 更完整的写法:print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • 默认情况下,将值打印到流或 sys.stdout
  • 可选关键字参数:
    1. file:类似于文件的对象(流);默认为当前的 sys.stdout
    2. sep:在值之间插入的字符串,默认为空格
    3. end:在最后一个值后追加的字符串,默认为换行符
    4. flush:whether to forcibly flush the stream 是否强制刷新数据流?
    5. fileflush 是要挖坑的节奏,待我学完来填平,编码 Py011-1
  • 示例
# print()

name = "YorkFish"

print(name + name)
print(name, name)           # 注意输出时有空格
print(name, name, sep='')   # sep 设置为不空格
print()                     # 输出一次换行符
print(name, end='\n\n')     # windows 下输出两次换行符
print(name, end=' --- ')    # 意味着不换行
print(name)
  • 运行结果

YorkFishYorkFish

YorkFish YorkFish

YorkFishYorkFish

YorkFish --- YorkFish

  • 不直观?来张截图:

3. format_map()

  • 释义:使用映射中的替换返回 S 的格式化版本
  • 示例
# 例3 没学到,只好从官方文档中找了个例子

class Default(dict):
     def __missing__(self, key):
         return key

print('{name} was born in {country}'.format_map(Default(name='Guido')))
  • 运行结果

Guido was born in country

  • 挖个坑,日后填平,编号 Py011-2

4. replace(old, new[, count])

  • 释义:
    1. 将字符串中的 old 子字符串替换成 new 子字符串
    2. 如果 count 指定,则替换不超过 count
  • 示例
# 例4

str4 = "All things in their being are good for something."

print(str4.replace('i', 'I'))
print(str4.replace('i', 'I', 3))
  • 运行结果

All thIngs In theIr beIng are good for somethIng.

All thIngs In theIr being are good for something.


5. split(step=None, maxsplit=-1)

  • 释义:
    1. 返回字符串中的单词列表,使用 sep 作为分隔符字符串
    2. 不带参数默认以空格为分隔符切片字符串
    3. 如果 maxsplit 参数有设置,则仅分隔 maxsplit 个子字符串,返回切片后的子字符串拼接的列表
  • 示例
# 例5

name5_1 = "Y.o.r.k.F.i.s.h"
name5_2 = "Y.o.r.k.F.i.s.h.."

print(name5_1.split('.'))
print(name5_1.split('.',maxsplit=4))
print(name5_2.split('.'))       # . 前的空字符算一个;. 后也算一个
  • 运行结果

['Y', 'o', 'r', 'k', 'F', 'i', 's', 'h']

['Y', 'o', 'r', 'k', 'F.i.s.h']

['Y', 'o', 'r', 'k', 'F', 'i', 's', 'h', '', '']

  • 亲兄弟:rsplit(sep=None, maxsplit=-1)
    • 类似于 split(step=None, maxsplit=-1),不过是从右边开始分隔

6. splitlines([keepends])

  • 释义:
    1. 按照 \n 分隔,返回一个包含各行作为元素的列表
    2. 如果 keepends 参数指定,则返回前 keepends
  • 示例
# 例6.1

str6 = "Cease to struggle \nand you cease to live.\n(Thomas Carlyle)"

print(str6.splitlines())        # 拆分后去掉换行符
print(str6.splitlines(True))    # 若 keepends 为 True,保留换行符
  • 运行结果

['Cease to struggle ', 'and you cease to live.', '(Thomas Carlyle)']

['Cease to struggle \n', 'and you cease to live.\n', '(Thomas Carlyle)']


  • splitlines() 与 split() 的区别
# 例6.2

print(''.splitlines())
print(''.split('\n'))   # 注意两者的区别

print("love at first sight.\n".splitlines())
print("love at first sight.\n".split('\n'))
  • 运行结果

[]

['']

['love at first sight.']

['love at first sight.', '']


7. startswith(prefix[, start[, end]])

  • 释义:
    1. 检查字符串是否以指定前缀 prefix 开头,prefix 只是代号,可以是任意字符串
    2. 如果是则返回 True,否则返回 False
    3. startend 与之前样,可指定开头或指定区域
  • 示例
# 例7

str7 = "The best is yet to come."

print (str7.startswith('The'))
print (str7.startswith('is', 9))
print (str7.startswith('best', 4, 7))   # 和 endswith() 有些像,区域要大于指定字符长度
print (str7.startswith('best', 4, 8))
  • 运行结果

True

True

False

True

  • 表兄弟:endswith(sub[, start[, end]])第一弹

8. swapcase()

  • 释义:翻转字符串中的大小写
  • 示例
# 例8

name8 = "YorkFish"
print(name8.swapcase())
  • 运行结果

yORKfISH


9. title()

  • 释义:
    1. 返回“标题化”的字符串
    2. 标题化:所有的单词都是以大写开始,其余字母均小写
  • 示例
# 例9

str9 = "the great gatsby"
print(str9.title())
  • 运行结果

The Great Gatsby


10. zfill(width)

  • 释义:
    1. 返回长度为 width 的字符串
    2. 原字符串右对齐
    3. width 大于字符串长度,前边用 0 填充
  • 示例
# 例10

name10 = "YorkFish"

print(name10.zfill(5))
print(name10.zfill(20))
print(name10.zfill())
  • 运行结果

YorkFish

000000000000YorkFish

TypeError……zfill() takes exactly one argument (0 given)

报错是因为没有输入 width 参数。

别的也是:若方法的小括号中有参数,并且 1. 没有用中括号括起来,2. 没有默认值,都需要填上。


(元气大伤!)

猜你喜欢

转载自www.cnblogs.com/yorkyu/p/10268679.html
011
今日推荐