字符串操作
1.字符串的翻轉
# 方式一 s = 'hello world' print(s[::-1) # 方式二 from functools import reduce print(reduce(lambda x,y:y+x, s))
2.判斷字符串是否是回文
利用字符串翻轉操作可以查看字符串是否回文
s1 = 'abccba'
s2 = 'abcde'
def func(s):
if s == s[::-1]:
print(‘回文’)
else:
print('不回文')
func(s1)
func(s2)
3.尋找字符串中唯一的元素
去重操作可以借助 set 來進行
# 字符串 s1 = 'wwweeerftttg' print(''.join(set(s1))) # ftgwer # 列表 l1 = [2, 4, 5, 6, 7, 1, 2] print(list(set(l1))) # [1, 2, 4, 5, 6, 7]
4.判斷字符串所含元素是否相同
判斷字符串中包含的元素是否相同,無論字符串中元素順序如何,只要包含相同的元素和數量,就認為其是相同的。
from collections import Counter s1, s2, s3 = 'asdf', 'fdsa', 'sfad' c1, c2, c3 = Counter(s1), Counter(s2), Counter(s3) if c1 == c2 and c2 == c3: print('符合')
列表操作
1.將嵌套列表展開
from iteration_utilities import deepflatten #Python小白學習交流群:153708845 l = [[12, 5, 3], [2. 4, [5], [6, 9, 7]], ] print(list(deepflatten(l)))
2.從任意長度的可迭代對象中分解元素
first, *middle, last = grades #*表達式可以用來將一個含有N個元素的數據結構類型分解成所需的幾部分
3.找到最大或最小的N個元素
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # [42, 37, 23]
print(heapq.nsmallest(3,nums)) # [-4, 1, 2]
# 根據指定的鍵得到最小的3個元素
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
其他
1.檢查對象的內存占用情況
import sys s1 = 'a' s2 = 'aaddf' n1 = 32 print(sys.getsizeof(s1)) # 50 print(sys.getsizeof(s2)) # 54 print(sys.getsizeof(n1)) # 28
2.print操作
# print輸出到文件
with open('somefile.txt', 'rt') as f:
print('Hello World!', file=f)
f.close()
# 以不同的分隔符或行結尾符完成打印
print('GKY',1995,5,18, sep='-',end='!!
') # GKY-1995-5-18!!
3.讀寫壓縮的文件
import gzip
with open('somefile.gz', 'rt') as f:
text = f.read()
f.close()
#Python小白學習交流群:153708845
import bz2
with open('somefile.bz2', 'rt') as f:
text = f.read()
f.close()
import gzip
with open('somefile.gz', 'wt') as f:
f.write(text)
f.close()
import bz2
with open('somefile.bz', 'wt') as f:
f.write(text)
f.close()
審核編輯:黃飛
-
字符串
+關注
關注
1文章
594瀏覽量
22967 -
python
+關注
關注
56文章
4849瀏覽量
89239
原文標題:Python中的幾個搔操作
文章出處:【微信號:magedu-Linux,微信公眾號:馬哥Linux運維】歡迎添加關注!文章轉載請注明出處。
發(fā)布評論請先 登錄
python學習--文件操作
python新手常見錯誤匯總
python常見異常類型
Python最常見的面試題解答
如何在環(huán)境安裝使用Python操作word

Python中的常見操作
評論