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

认识

Python Strings https://developers.google.com/edu/python/strings

格式 | format

python – How do I put a variable’s value inside a string (interpolate it into the string)? – Stack Overflow
https://www.cnblogs.com/alfred0311/p/7735539.html
http://lofic.github.io/tips/python-heredoc.html

# 格式化输出 %s & %d 等

# ----------------------------------------------------------------------------- # %

print("%s %s" % ("foo", "bar"))
print("Name:%-10s Age:%08d Height:%08.2f" % ("Alfred", 25, 1.70))


# ----------------------------------------------------------------------------- # f""

name = "John"
f"Hello, {name}."    # Hello, John.
f"Hello, {name:5s}." # Hello, John . # 固定宽度

# ----------------------------------------------------------------------------- # str.format()

"{name} was {place}".format(name='Louis', place='here')
"Hello, {}".format(name)
"For only {price:.2f} dollars!".format(price = 49)

截取 | str[start:end:step]

# ----------------------------------------------------------------------------- # str[start:end:step]

text = "Hello, World!"

print(text[2:5])    # 输出: llo
print(text[:5])     # 输出: Hello
print(text[7:])     # 输出: World!
print(text[-6:-1])  # 输出: World

# 使用步长
print(text[::2])    # 输出: Hlo ol!

# 反转字符串
print(text[::-1])   # 输出: !dlroW , olleH

分割 | split()

使用字符串切割字符串

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

替换 | replace()

str = "This is string example....wow!!! this is really string"
str.replace("is", "was")

去空 | 两边去空白字符

Python Trim String – rstrip(), lstrip(), strip()

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

增加宽度 | python – How to pad a string to a fixed length with spaces – Stack Overflow

'69'.rjust(5, '*') # => ***69
'69'.ljust(3, '#') # => 69#
'69'.zfill(8)      # => 00000069

'John'.ljust(15)   # with Whitespace

长度 | 计算某个字符串长度

len("foo")                                                                      # 3

为空 | 判断字符串为空

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

if not myString:
    # do stuff

编码 | 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')

注意,如上示例,编码与解码函数需要输出字节

编码转换

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

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

二进制 ⇔ 普通字符串

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

多上字符创 | 长文本 | Heredoc | Multiline String

python – heredoc or multiline string
Multiline String in Python – GeeksforGeeks

text="""{name}
was
{place}"""

text.format(name='Louis', place='here')

# 注 1:通过 {{ 来转义 { 字符;

// --------------------------------------------------------- //

colors = ("multi-line string"
		"red \n"
		"blue \n"
		"green \n"
		"yellow \n"
		)

multi-line stringred 
blue 
green 
yellow 

参考文献

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?