Python 基础(1) string

飘往NBviewer版本的捷径

Table of Contents

string编辑

修整截断头尾strip()

str.strip([chars]) 去掉字符串左右两端的空格,返回字新的字符串对象

1
2
3
4
5
6
'''
Return a copy of the string with leading and trailing whitespace remove.
If chars is given and not None, remove characters in chars instead.
'''
check = ' Everything is fine! '
check.strip()
'Everything is fine!'

如果chars参数指定了,则从字符串两端计算删除指定的 chars 的成员

1
2
#删除字符串两端的[E][e][v][!][ ]
check.strip('Eev! ')
'rything is fin'

右截断、左截断

  • 右删除str.rstrip([chars])
  • 左删除str.lstrip([chars])

innot in 操作

1
'Python' in 'Python is great!'
True
1
'PYTHON' in 'Python is great!'
False
1
'' in 'Python is great!'
True
1
'python' not in 'python and javascript' ## Matches case
False
  • The in and not in Operators with list
1
2
a = ['P', 'y', 't', 'h', 'o', 'n']
'p' in a
False

The upper(), lower(), isupper(), islower() string methods

string template 字符串模板

  • 可以预先定义sting模板,然后给模板中的制定替换文字做文字替换操作
1
2
3
4
from string import Template #先引入 string.Template
language = 'Python'
t = Template('$lang is great! $name likes play with $lang')
t.substitute(lang=language, name='Dummy') ## Substitutes name with language variable
'Python is great! Dummy likes play with Python'

Pyperclip

  • Pyperclip is python library that help us easily copy and paste string
  • First Install it using pip
1
pip install pyperclip
1
2
3
import pyperclip
pyperclip.copy('Hello World') ## Copy Hello World
pyperclip.paste()

string编码和解码

编码(bytes to string)

chr(i) buildin function 将制定整数unicode编码返回对应的字符string

1
print(chr(97))
a

bytes.decode(encoding="utf-8", errors="strict")

  • 根据bytes返回默认utf8编码字符串
1
b'\xe6\x88\x91\xe4\xbb\xac'.decode()
'我们'

str(object=b'', encoding='utf-8', errors='strict') buildin function

  • 根据bytes返回制定编码方式的字符串
1
str(b'\xe6\x88\x91\xe4\xbb\xac', 'utf8')
'我们'

解码(string to bytes)

ord(c) buildin function

  • 根据给定的字符,返回代表该字符的unicode十进制整数编码
1
2
print(ord('a'))
print(ord('我'))
97
25105

str.encode(self, /, encoding='utf-8', errors='strict') 将string返回默认utf8 unicode字节

  • 返回bytes对象
1
'我们'.encode()
b'\xe6\x88\x91\xe4\xbb\xac'

class bytes([source[, encoding[, errors]]]) buildin function

1
bytes('我们', 'utf8')
b'\xe6\x88\x91\xe4\xbb\xac'