python 字符串分割_Python 中的字符串处理详解(原始字符串、分割、转码等)

字符串

Python 中没有单独的字符类型,字符串属于不可变类型:

>>> str = 'abc'

>>> str[0] = 'a'

Traceback (most recent call last):

File "", line 1, in

TypeError: 'str' object does not support item assignment

使用三引号:"""...""" 或 '''...''',得到的字符串所见即所得:

>>> "hello " "world" # 会被自动转换为hello world

'hello world'

分割/拼接

字符串分割函数主要有 str.split('=') 和 str.partition('='),区别在于:

split 输出的是列表,partition 输出的是元组

partition 的元组有三个元素,包括分割符('='),而 split 输出只有两个元素。

split 的字符参数若在字符串中不存在会报错,而 partition 不会

将列表 / 元组中的所有元素拼接成一个字符串:

str1 = ''.join(list1)

str2 = ''.join(tuple1)

将两个列表 / 元组中的所有元素按照下标合并:

# 例如,将列表en_sections中的字符串和zh_sections中的字符串两两拼接,变成一个新的列表

sections = [a + b for a, b in zip(en_sections, zh_sections)]

>>>a = [1,2,3]

>>> c = [4,5,6,7,8]

>>> list(zip(a,c))

[(1, 4), (2, 5), (3, 6)]

原始字符串

原始字符串中包括换行符之类的特殊符号

print(r'string')

print(repr(str))

>>> r'\\'

'\\\\'

>>> r'\' # 注意不能以奇数个反斜杠结尾,这样最后一个引号会被视作字符串的一部分

File "", line 1

r'\'

^

SyntaxError: EOL while scanning string literal

去除空格

>>> str = ' a bc '

>>> str.strip()

'a bc'

>>> str.lstrip()

'a bc '

>>> str.rstrip()

' a bc'

编码转换

字符 ↔ ASCII / Unicode,使用 ord() 和 chr() 函数

ASCII 编码实际上是 UTF-8 编码的一部分

UTF-8 中使用三个字节表示一个汉字

UCS2,即两个字节表示一个字符

>>> ord('A')

65

>>> chr(97)

'a'

>>> hex(ord('龙'))

'0x9f99'

>>> chr(0x9f99)

'龙'

>>> '\u9f99'

'龙'

>>> '龙'.encode('utf-8')

b'\xe9\xbe\x99'

>>> b'\xe9\xbe\x99'.decode('utf-8')

'龙'

URL 编码的转换:

# Python2 的解码方法

if sys.version_info[0] < 3:

import urllib

return urllib.unquote_plus(text)

return urllib.unquote(text)

# Python2 的编码方法

if isinstance(text, unicode):

text = text.encode('utf-8', 'ignore')

return urllib.quote_plus(text)

return urlparse.quote(text)

# Python3 的解码方法

import urllib.parse

return urllib.parse.unquote_plus(text)

return urllib.parse.unquote(text)

# Python3 的编码方法

return urllib.parse.quote_plus(text)

return urllib.parse.quote(text)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值