Python編程技巧:那些年后悔沒有早知道String模塊的這些寶藏功能
剛學習Python的時候,你是否遇到過這樣的練習?
- 打印英文字母表(26個連續(xù)字母)
- 打印所有數(shù)字(0-9)
- ...
比如前兩個,當時只能老老實實的逐個手動輸入“abcdefghijklmnopkrstuvwxyz”和“0123456789”給 print 函數(shù),向下面這樣:
print('abcdefghijklmnopkrstuvwxyz')
print('0123456789')
# abcdefghijklmnopkrstuvwxyz
# 0123456789
今天看書才發(fā)現(xiàn)一個更省事的方法,Python的 string 模塊里面定義一些常用的常量,就包括字母表、數(shù)字等等,只需要調(diào)用相關(guān)的常量屬性就可以實現(xiàn),代碼既簡潔又高效。從此告別傻傻地手動輸入。
本文,我將向大家介紹 string 模塊的一些寶藏功能,讓你寫出更高效、更優(yōu)雅的代碼。
話不多說,開始上課!注意~~前方高能,美女助教引領(lǐng)大家快速進入狀態(tài),還在打瞌睡的請打起精神??????
內(nèi)置string模塊
內(nèi)置,意味著我們不需要單獨安裝它,只需要在腳本頂部導入它即可使用。該模塊包括下面這些很有用的魔法屬性:
1.string.ascii_lowercase
一次性輸出所有26個小寫字母,再也不用一個個手動輸入啦!
import string
print(f'Alphabet by lowercase: {string.ascii_lowercase}')
# Alphabet by lowercase: abcdefghijklmnopqrstuvwxyz
2.string.ascii_uppercase
與 ascii_lowercase 相反,這個屬性用于一次性輸出所有大寫字母:
print(f'Alphabet by uppercase: {string.ascii_uppercase}')
# Alphabet by uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ
3.string.whitespace
這個屬性可以一次性輸出所有空格類型(白色空格、制表符、換行符等),注意,為了看到效果,請將結(jié)果轉(zhuǎn)換為列表后輸出,否則直接打印的話會是一片空白:
print(f'All whitespaces: {[string.whitespace]}')
# All whitespaces: [' \t\n\r\x0b\x0c']
4.string.punctuation
這個屬性可用于一次性輸出所有標點符號:
print(f'All punctuations: {string.punctuation}')
# All punctuations: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
5.string.digits
一次性打印出所有數(shù)字:
print(f'All numbers: {string.digits}')
# All numbers: 0123456789
6.string.ascii_letters
這個屬性是 ascii_lowercase 和 ascii_uppercase 的組合,即一次性打印出所有大小寫字母:
print(f'Alpabet letters: {string.ascii_letters}')
# Alpabet letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
7.string.hexdigits
這個屬性可以輸出代表十六進制數(shù)字的所有字符:
print(f'Hex digits: {string.hexdigits}')
# Hex digits: 0123456789abcdefABCDEF
8.string.octdigits
這個屬性則用于輸出代表八進制的所有字符,與 string.digits 的輸出結(jié)果相比,少了“89”:
print(f'Octal digits: {string.octdigits}')
# Octal digits: 01234567
這些預定義的字符串常量可以用于多種場景,例如數(shù)據(jù)驗證、數(shù)據(jù)清洗、字符分類和更多。例如,使用 string.digits 可以快速檢查或過濾出字符串中的數(shù)字,或者使用 string.punctuation 來移除文本中的所有標點符號。
string 模塊本身主要提供的是這些預定義常量,而不提供特殊的方法或函數(shù)。但這些常量在結(jié)合正則表達式或其他字符串處理功能時,可以讓你的代碼更簡潔和優(yōu)雅,更加 Pythonic。
例如,如果需要檢查一個字符串是否只包含字母和數(shù)字,可以結(jié)合使用 string.ascii_letters 和 string.digits 來創(chuàng)建一個檢查用的集合:
import string
allowed_chars = set(string.ascii_letters + string.digits)
def is_alphanumeric(s):
return set(s).issubset(allowed_chars)
test_str = 'I love Python programming, 666!'
print(is_alphanumeric(test_str))
# False
進階用法
在Python標準庫的 string 模塊中,我已經(jīng)列出了主要的預定義字符串常量,這些常量基本涵蓋了模塊的核心功能。這些常量主要用于提供方便的字符集,幫助程序員在處理文本數(shù)據(jù)時避免手動鍵入這些常見的字符列表。
除了前面提到的常量,string 模塊沒有提供其他的內(nèi)置方法或?qū)傩浴K脑O(shè)計主要是為了提供簡便的、預定義的字符集,這些字符集經(jīng)常在文本處理中使用。
進階使用
雖然 string 模塊本身功能相對簡單,但可以與Python的其他文本處理功能如正則表達式 (re 模塊)、文本轉(zhuǎn)換和編碼等結(jié)合使用來實現(xiàn)更復雜的功能。這里是一些實用的示例,展示如何利用 string 模塊來處理更高級的文本問題:
- 生成隨機字符串:使用string模塊中的字符集合,結(jié)合random模塊,可以輕松生成隨機密碼或標識符。
import string
import random
def get_random_string(length=10):
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
print(f'Random password: {get_random_string()}')
print(f'Random identifier: {get_random_string(length=12)}')
# Random password: wc7m5wD2KM
# Random identifier: SHrea9RchD4A
- 清洗字符串:移除字符串中的特定字符集,比如所有標點符號。
import string
def remove_punctuation(s):
return s.translate(str.maketrans('', '', string.punctuation))
test_str = 'My email is myname@example.com!'
print(f'Removed punctuation: {remove_punctuation(test_str)}')
# Removed punctuation: My email is mynameexamplecom
- 字符分類:可以使用string模塊來快速分類字符串中的字符,如分離字母和數(shù)字。
import string
def classify_chars(s):
letters = [ch for ch in s if ch in string.ascii_letters]
digits = [ch for ch in s if ch in string.digits]
return letters, digits
結(jié)論
盡管 string 模塊提供的內(nèi)容相對簡單,但這些工具非常適合與 Python 中的其他功能相結(jié)合,創(chuàng)建更復雜的文本處理解決方案。這種模塊化的方法不僅保持代碼的簡潔性,也提高了開發(fā)效率。
好啦,今天分享就到此結(jié)束啦!趕緊去用起來吧!