format(数据,'格式')
>>> format(532.26, '10.3f')
' 532.260'
>>> format('你好呀笨蛋', '>20s')
' 你好呀笨蛋'
>>> format(0.001234, '10.3%')
' 0.123%'
>>> format(2, '06b')
'000010'
'{0: 格式}, {1: 格式},....'.format(数据, 数据2,....)
>>> '输出小数:{0: >10.3f}\n输出字符串:{1: <20s}\n输出百分数{2: >10.3%}'.format(532.26, '你好呀笨蛋', 0.0011234)
'输出小数: 532.260\n输出字符串:你好呀笨蛋 \n输出百分数 0.112%'
new_string = string.center(长度, 填充单字符)
>>> # 字符串对齐并补全
>>> 'hello cc'.center(20, '*')
'******hello cc******'
>>> 'hello cc'.rjust(20, '*')
'************hello cc'
>>> 'hello cc'.ljust(20, '*')
'hello cc************'
>>> 'ccc'.center(20, '=')
'========ccc========='
查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次或最后一次出现的位置:
string.find(substring[, start[, end]]) -> int
>>> text = '''
东边来个小朋友叫小松,手里拿着一捆葱。
西边来个小朋友叫小丛,手里拿着小闹钟。
小松手里葱捆得松,掉在地上一些葱。
小丛忙放闹钟去拾葱,帮助小松捆紧葱.
小松夸小丛像雷锋,小丛说小松爱劳动。
'''
>>> for i, ch in enumerate(text):
if i == text.find(ch): # 当前ch是首次出现的ch,才记录
print('字符{0}首次出现下标为{1}'.format(ch, i))
查找一个字符串在另一个字符串中出现的次数:string.count(substring)
S.endswith(suffix[, start[, end]]) -> bool
>>> import os
# 文稿下文件
>>> [filename for filename in os.listdir()]
['.DS_Store', 'Nuts', '.localized', '二阶段锁.xlsx', 'GTA Vice City User Files', 'totalLength.plist', 'Python3萌新入门笔记.pdf', 'TencentMeeting', '.UTSystemConfig', '1400115281_report_pb.dump', 'src']
# 找到以pdf结尾的文件
>>> [filename for filename in os.listdir() if filename.endswith('.pdf')]
['Python3萌新入门笔记.pdf']
string.split(分隔符默认为所有空白符, maxsplit = n)
:>>> string = ' apple,peach, peach,pear,orange'
>>> string.split()
['apple,peach,', 'peach,pear,orange']
>>> string = ' apple,peach, peach,pear,orange'
>>> string.split(',')
[' apple', 'peach', ' peach', 'pear', 'orange']
>>> string.split('peach')
[' apple,', ', ', ',pear,orange']
>>> string = ' apple,peach, peach,pear,orange'
>>> string.split(maxsplit = 2)
['apple,peach,', 'peach,pear,orange']
直接re
>>> text = 'alpha. beta....gamma delta'
>>> re.split(r'[. ]+', text)
['alpha', 'beta', 'gamma', 'delta']
用正则对象
>>> text = 'alpha. beta....gamma delta'
>>> pattern = re.compile(r'[. ]+')
>>> pattern.split(text, maxsplit = 2)
['alpha', 'beta', 'gamma delta']
永远结果是三份:左中右 string.[r]partition(中间字符串)
>>> string = ' apple,peach, peach,pear,orange'
>>> string.partition('peach')
(' apple,', 'peach', ', peach,pear,orange')
string = '连接符'.join(字符串列表)
>>> '::'.join(['aa', 'bb', 'cc'])
'aa::bb::cc'
>>> '::'.join(['aa'] * 5)
'aa::aa::aa::aa::aa'
>>> ''.join(['aa', 'bb', 'cc'])
'aabbcc'
>>> '一'.isnumeric()
True
>>> 'ⅣⅢⅩ'.isnumeric()
True
new_string = string.replace('word', 'replacestring', 替换次数)
如下替换cc和dad都是不重叠的
>>> 'cccdadad'.replace('cc', '*')
'*cdadad'
>>> 'cccdadad'.replace('dad', '*')
'ccc*ad'
'''1. 遍历'''
res, i = 0, 0
while i < len(s1) - len(s2) + 1:
if s1[i:i + len(s2)] == s2:
res += 1
i += len(s2)
else:
i += 1
return res
''' 2. split分割'''
return len(s1.split(s2)) - 1
'''3. replace替换的特性:不重叠替换,个人觉得最好理解'''
s = s1.replace(s2, '*')
return s.count('*')
>>> words = ['asshole', 'stupid', 'kill']
>>> for word in words:
if word in 'i will kill you':
'i will kill you'.replace(word, '*****')
'i will ***** you'
1、映射表:table = ''.maketrans(string1, string2)
2、开始映射:new_string = string.translate(table)
>>> table = ''.maketrans('12345', '一二三四五')
>>> string = '42352346'
>>> new_string = string.translate(table)
>>> new_string
'四二三五二三四6'
>>> table
{49: 19968, 50: 20108, 51: 19977, 52: 22235, 53: 20116}
from string import ascii_letters, ascii_lowercase, ascii_uppercase
def kaisaEncrypt(string, k):
# 每个字母替换为后面k个
new_lower = ascii_lowercase[k:] + ascii_lowercase[:k]
new_upper = ascii_uppercase[k:] + ascii_uppercase[:k]
table = ''.maketrans(ascii_letters, new_lower + new_upper)
new_string = string.translate(table)
return new_string
# 是否解密成功
def check(temp_string) -> bool:
# 不唯一:我们对每次尝试解密的结果测试是否含有至少两个常见单词,若有,则认为解密成功
mostCommonWords = ('the', 'is', 'to', 'not', 'have', 'than', 'for', 'like')
# 如果word在temp_string中,则元祖放一个1
return sum(1 for word in mostCommonWords if word in temp_string) >= 2
def kaisaDecrypt(new_string):
# 加密是后移字母,一共有26种情况,一一测试
for i in range(1, 26):
temp_string = kaisaEncrypt(new_string, -i)
if check(temp_string)== True:
return temp_string
if __name__ == '__main__':
string = "Python is a greate programming language. I like it!"
new_string = kaisaEncrypt(string, 3)
print(kaisaDecrypt(new_string))
new_string = string.strip(字符/字符串)
规则:看外侧有啥,再看参数有没有该字符,有则删除,没有则删不掉
>>> ' hello world '.strip()
'hello world'
>>> 'dffdfaaafff'.strip('a')
'dffdfaaafff'
>>> 'afffaffaa'.strip('a')
'fffaff'
>>> 'aaaddfffccc'.strip('af')
'ddfffccc'
>>> 'aabbccddeeeffg'.strip('gbaefcd')
''
>>> 'aadfaaffffaaddaa'.lstrip('a')
'dfaaffffaaddaa'
>>> 'aadfaaffffaaddaa'.rstrip('a')
'aadfaaffffaadd'
规范化每行输出:姓名:张三…
>>> text = '''姓名:张三
年龄:39
性别男
职业 学生
籍贯: 地球'''
>>> lst_lines = [line.strip() for line in text.split('\n')]
>>> lst_lines
['姓名:张三', '年龄:39', '性别男', '职业 学生', '籍贯: 地球']
>>> for item in lst_lines:
print(item[:2], item[2:].strip(': '), sep = ':')
姓名:张三
年龄:39
性别:男
职业:学生
籍贯:地球
参数必须是字符串!
tip: 经leetcode解题过程发现:
eval链接字符串运算比直接int(string)再做运算,或者ord(‘string’)-ord(‘0’)慢的多
>>> 1,2,3
(1, 2, 3)
>>> 1,2,
(1, 2)
>>> eval('1,2,')
(1, 2)
>>> eval('1 2')
Traceback (most recent call last):
File "" , line 1, in <module>
eval('1 2')
File "" , line 1
1 2
^
SyntaxError: unexpected EOF while parsing
>>> eval('string')
Traceback (most recent call last):
File "" , line 1, in <module>
eval('string')
File "" , line 1, in <module>
NameError: name 'string' is not defined
>>> eval("'string'")
'string'
一般\n, \t算一个字符,如果加上转义符号r或者 \则变成单纯两个字符:\ 和n
>>> len(r'\ngood')
6
>>> len('\\ngood')
6
>>> len('\ngood')
5
字符串s=‘a\nb\tc’,则len(s)的值是( )。C
A.7 B.6 C.5 D.4
Python语句print(r"\nGood")的运行结果是( \nGood )。