博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PyTips 0x07 - Python 字符串
阅读量:7072 次
发布时间:2019-06-28

本文共 2983 字,大约阅读时间需要 9 分钟。

项目地址:

所有用过 Python (2&3)的人应该都看过下面两行错误信息:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte

这就是 Python 界的"锟斤拷"!

今天和接下来几期的内容将主要关注 Python 中的字符串(str)、字节(bytes)及两者之间的相互转换(encode/decode)。也许不能让你突然间解决所有乱码问题,但希望可以帮助你迅速找到问题所在。

定义

Python 中对字符串的定义如下:

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.

Python 3.5 中字符串是由一系列 Unicode 码位(code point)所组成的不可变序列

('S' 'T' 'R' 'I' 'N' 'G')
'STRING'

不可变是指无法对字符串本身进行更改操作:

s = 'Hello'print(s[3])s[3] = 'o'
l
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)
in
() 1 s = 'Hello' 2 print(s[3])----> 3 s[3] = 'o'TypeError: 'str' object does not support item assignment

序列(sequence)则是指字符串继承序列类型(list/tuple/range)的通用操作:

[i.upper() for i in "hello"]
['H', 'E', 'L', 'L', 'O']

至于 Unicode 暂时可以看作一张非常大的地图,这张地图里面记录了世界上所有的符号,而码位则是每个符号所对应的坐标(具体内容将在后面的几期介绍)。

s = '雨'print(s)print(len(s))print(s.encode())
雨1b'\xe9\x9b\xa8'

常用操作

  • len:字符串长度;

  • split & join

  • find & index

  • strip

  • upper & lower & swapcase & title & capitalize

  • endswith & startswith & is*

  • zfill

# split & joins = "Hello world!"print(",".join(s.split())) # 常用的切分 & 重组操作"https://github.com/rainyear/pytips".split("/", 2) # 限定切分次数
Hello,world!
['https:', '', 'github.com/rainyear/pytips']
s = "coffee"print(s.find('f'))    # 从左至右搜索,返回第一个下标print(s.rfind('f'))   # 从右至左搜索,返回第一个下表print(s.find('a'))    # 若不存在则返回 -1print(s.index('a'))   # 若不存在则抛出 ValueError,其余与 find 相同
23-1
---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)
in
() 4 5 print(s.find('a')) # 若不存在则返回 -1----> 6 print(s.index('a')) # 若不存在则抛出 ValueError,其余与 find 相同ValueError: substring not found
print(" hello world    ".strip())print("helloworld".strip("heo"))print("["+"          i         ".lstrip() +"]")print("["+"          i         ".rstrip() +"]")
hello worldlloworld[i         ][          i]
print("{}\n{}\n{}\n{}\n{}".format(    "hello, WORLD".upper(),    "hello, WORLD".lower(),    "hello, WORLD".swapcase(),    "hello, WORLD".capitalize(),    "hello, WORLD".title()))
HELLO, WORLDhello, worldHELLO, worldHello, worldHello, World
print("""{}|{}{}|{}{}|{}{}|{}{}|{}{}|{}""".format(    "Python".startswith("P"),"Python".startswith("y"),    "Python".endswith("n"),"Python".endswith("o"),    "i23o6".isalnum(),"1 2 3 0 6".isalnum(),    "isalpha".isalpha(),"isa1pha".isalpha(),    "python".islower(),"Python".islower(),    "PYTHON".isupper(),"Python".isupper(),))
True|FalseTrue|FalseTrue|FalseTrue|FalseTrue|FalseTrue|False
"101".zfill(8)
'00000101'

format / encode

格式化输出 format 是非常有用的工具,将会单独进行介绍;encode 会在 bytes-decode-Unicode-encode-bytes 中详细介绍。

欢迎关注公众号 PyHub!

转载地址:http://cgkml.baihongyu.com/

你可能感兴趣的文章
利用Sympy计算sin1°的最小多项式
查看>>
Vuejs响应式原理
查看>>
【Nebula系列】C++反射机制:可变参数模板实现C++反射
查看>>
mac 终端 常用命令
查看>>
2016年人工智能产业梳理:一朝引爆,稳步前进(下篇)
查看>>
django 1.8 官方文档翻译:5-1-2 表单API
查看>>
区块链将会怎样颠覆Google、Amazon、Facebook和Apple?
查看>>
VR直播很火,但能取代传统电视直播吗?
查看>>
[转]区块链代码快速学习实践
查看>>
QuickBI助你成为分析师——计算字段功能
查看>>
《王牌特工2》情景再现,Youbionic推出可穿戴式机械手
查看>>
雪城大学信息安全讲义 五、竞态条件
查看>>
干货分享:MySQL之化险为夷的【钻石】抢购风暴
查看>>
量子通信能否跨越“死亡之谷”?2017年市场化的量子通信产品可能产生
查看>>
有序顺序表合并
查看>>
设计模式-观察者模式
查看>>
Spring4-自动装配Beans-按属性名称自动装配
查看>>
精通比特币系列---挖矿与共识
查看>>
to use extended Windows dialogs
查看>>
3A级VR游戏将至?汪丛青力挺G胖正在开发的三款VR游戏
查看>>