「Python」- 常用字符串操作(学习笔记)

  CREATED BY JENKINSBOT

最常用的字符串操作

# 长度:计算某个字符串长度
len("foo")  # 3

# 截取:截取字符串的某段
str = "foo-bar"
str[0:4]  # foo-

# 分割:使用字符串切割字符串
txt = "127.0.0.1:8080"
txt.split(":")  # ['127.0.0.1', '8080']

# 替换:替换字符串的某些内容
str = "This is string example....wow!!! this is really string"
str.replace("is", "was")

两边去空白字符

"".strip()
"".lstrip()
"".rstrip()

格式化字符串

print("%s %s" % ("foo", "bar"))

编码转换

urllib.parse.quote(query) # 该函数不转码斜线
urllib.parse.quote_plus(query) # 转码空格到加号的所有字符

# Unicode decode
str.encode("utf-8").decode("unicode_escape")

二进制 ⇔ 普通字符串

b'bin string'.decode('ascii')

参考文献

Python Strings
How to convert ‘binary string’ to normal string in Python3?
How to encode URLs in Python
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
Python Trim String – rstrip(), lstrip(), strip()