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

最常用的字符串操作

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

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

# 分割:使用字符串切割字符串
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")

判断字符串为空

python – How to check if the string is empty? – Stack Overflow

if not myString:
    # do stuff

两边去空白字符

"".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')

Base64, Endcoding and Decoding

Encoding and Decoding Base64 Strings in Python

import base64

message = "Python is fun"
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')


import base64

base64_message = 'UHl0aG9uIGlzIGZ1bg=='
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.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()