python-string

r or b or f prefix string

r means the string will be treated as raw string.

dirname = r'C:\temp\parts'
# the literal should become a bytes literal in Python 3
my_string = b'The string'

f py3 new style format

f"Hello, {name}. You are {age}."

# 不足3位补零
f'{close_price-buy_price:03.2f}'

now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')

val = 12.3

print(f'{val:.2f}')
print(f'{val:.5f}')

编码

查找

print info.find('a')##从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
print info.find('a',1)##从下标1开始,查找在字符串里第一个出现的子串:返回结果3

index方法是在字符串里查找子串第一次出现的位置,类似字符串的find方法,
不过比find方法更好的是,如果查找不到子串,会抛出异常,而不是返回-1

rfind和rindex方法用法和上面一样,只是从字符串的末尾开始查找。

获取子串

string = "freeCodeCamp"
print(string[0:5])

replace

str.replace(old, new[, max])

Live Demo
#!/usr/bin/python

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

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

删除最后一个字符

st = "abcdefghij"
st = st[:-1]

分割字符串

str1 = 'ab c\n\nde fg\rkl\r\n'
print str1.splitlines();

str2 = 'ab c\n\nde fg\rkl\r\n'
print str2.splitlines(True)

['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

txt = "welcome to the jungle"
x = txt.split()
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)

多行字符串

str1 = '''Le vent se lève, il faut tenter de vivre. 
起风了,唯有努力生存。
(纵有疾风起,人生不言弃。)'''

sql = ("select *"
" from a "
" where b = 1")

开头结尾

# startswith()
# endswith()

if dir.endswith(it):
pass

字符串转数字

int('0x10', 16)  ==>  16

float
try:
lng = float(row[1])/10^6
lat = float(row[2])/10^6
except ValueError:
print('invalid input %s' % (input))

str(int_value)
int(str_value)

数字转字符串

dataSend += '%.6f,%.6f;' % (lng, lat)

字符串转 byte 数组

data = "8D 01 45 01 00 00 00 00 00 00 00 00 00"
data = data.replace(' ', '')
result = bytearray.fromhex(data)

去空白字符

# 去两端空白
s.strip()
# 去左端空白
s.lstrip()
# 去右端空白
s.rstrip()

# 去空白,包括中间部分
s.replace(' ', '')

字符串转 json

import json
str = '{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}'

j = json.loads(str)

print(j)
print(type(j))

json 转字符串

import json
j = {"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}

str = json.dumps(j)

print(str)
print(type(str))

format

f-strings 格式

基本用法

>>> name = "Tom"
>>> age = 3
>>> f"His name is {name}, he's {age} years old."
>>> "His name is Tom, he's 3 years old."

>>> f"Hey {name}, there's a {errno:#x} error!"
"Hey Bob, there's a 0xbadc0ffee error!"

now = datetime.datetime.now()

print(f'{now:%Y-%m-%d %H:%M}')
2019-05-11 22:39

# 浮点数
val = 12.3

print(f'{val:.2f}')
print(f'{val:.5f}')
12.30
12.30000

# 宽度

for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')

01 1 1
02 4 8
03 9 27
04 16 64

str.format() 格式

ref.

'{} {}'.format('one', 'two')
'{} {}'.format(1, 2)
'{1} {0}'.format('one', 'two')
浮点数格式化 23.2300
"{:10.4f}".format(x)
num_str2 = '{:02d}'.format(i)
num_str1 = '123'
num_str2 = '-123'

print(num_str1.zfill(5)) # 00123
print(num_str2.zfill(5)) # -0123

'rise05={:10.2f}'.format(i)

list to str

', '.join(mylist)

数字操作

# 小数精度
>>> PI = 3.141592653
>>> f"Pi is {PI:.2f}"
>>> 'Pi is 3.14'

# 进制转换
>>> f'int: 31, hex: {31:x}, oct: {31:o}'
'int: 31, hex: 1f, oct: 37'

表达式

# 数学运算
>>> f'He will be { age+1 } years old next year.'
>>> 'He will be 4 years old next year.'

## 对象操作
>>> spurs = {"Guard": "Parker", "Forward": "Duncan"}
>>> f"The {len(spurs)} players are: {spurs['Guard']} the guard, and {spurs['Forward']} the forward."
>>> 'The 2 players are: Parker the guard, and Duncan the forward.'

>>> f'Numbers from 1-10 are {[_ for _ in range(1, 11)]}'
>>> 'Numbers from 1-10 are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

排版格式

>>> def show_players():
print(f"{'Position':^10}{'Name':^10}")
for player in spurs:
print(f"{player:^10}{spurs[player]:^10}")
>>> show_players()
Position Name
Guard Parker
Forward Duncan

注意事项

{}内不能包含反斜杠\

bytes and str

文本总是 Unicode,由 str 类型表示,二进制数据则由 bytes 类型表示

str to bytes
b = bytes(s1, encoding='gbk')
b = a.encode(encoding='utf-8')

bytes to str
c = b.decode(encoding='utf-8')