我使用python处理字符串时,总是会忘记一些函数和方法,导致每次都要上网查阅资料。于是,我写下此篇文章,方便自己查询。

字符串可以像列表一样切片

一些转义字符

\t制表符
\n换行

常用方法

所有字母大写 upper()
所有字母小写 lower()
每个单词首字母大写 title()
判断是否以特定字符开始 startswith()
判断是否以特定字符结束 endswith()
删除左右空白字符(空格、回车、制表符) strip()可在括号中指定删除的字符,如果传入的是字符串,字符排列顺序不影响
删除右侧空白字符 rstrip()
删除左侧空白字符 lstrip()
删除前缀 removeprefix()

一些方法

判断是否所有字母大写 isupper()
判断是否所有字母小写 islower()
判断是否单词首字母大写 istitle()
判断非空字符串是否只包含空格、换行、制表符 isspace()
判断非空字符串是否只包含数字 isdecimal()
判断非空字符串是否只包含字母和数字 isalnum()
判断非空字符串是否只包含字母 isalpha()
将字符串列表中的字符串连接在一起 join()

1
2
3
4
5
6
7
8
9
10
11
12
spam1 = ' '
spam_list = ['have', 'a', 'good', 'time']
print(spam1.join(spam_list))
spam2 = ''
print(spam2.join(spam_list))
spam3 = '1'
print(spam3.join(spam_list))
"""输出结果
have a good time
haveagoodtime
have1a1good1time
"""

将字符串切割为列表 split()

1
2
3
4
5
6
7
8
string1 = 'have a good time'
string2 = 'have1a1good1time'
print(string1.split())
print(string2.split('1'))
""""输出结果
['have', 'a', 'good', 'time']
['have', 'a', 'good', 'time']
"""

对齐

右对齐 rjust()括号中参数为字符串长度,不足自动补空格
左对齐 ljust()
居中 center()

pyperclip库

向剪贴板接受文本或发送文本
向剪贴板发送文本 函数copy(‘需要发送到剪贴板的文本’)
从剪贴板接收文本 函数paste() 此函数的返回值是剪贴板最近一次的内容

口令保管箱(通过关键字将对应内容复制到剪贴板)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import sys, pyperclip

passwords = {'email': 'sbsajkvnaaoovnOSVNAN',
'blog': 'IAINAOojnoaOOAN',
'luggage': '116366'}
if len(sys.argv) < 2:
# 命令行参数列表sys.argv下标为0的元素是此文件的地址,之后的元素需要自己传入
print('请在cmd或终端传入关键字')
sys.exit()

account = sys.argv[1]
if account in passwords.keys():
# if account in passwords:
pyperclip.copy(passwords[account])
print(f'{account}的密码已复制到剪贴板。')
else:
print('你输入的账号不存在')

命令行参数传参方法:
python 文件地址 需要传入的参数
命令行参数传参方法

添加无序列表(每行开头添加*)

python之禅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

为python之禅添加无序列表(在每行开头加*)

1
2
3
4
5
6
7
8
import pyperclip

text = pyperclip.paste()
lines = text.split('\n')
for i in range(len(lines)):
lines[i] = '* ' + lines[i]
text = '\n'.join(lines)
pyperclip.copy(text)