新聞中心
在Python中,字符串是基本的不可變序列類型,用于表示文本,string模塊提供了一些有用的常量和函數(shù)來處理字符串。

1、string模塊中的常用常量:
string.ascii_letters:包含所有ASCII字母(大小寫)的字符串。
string.ascii_lowercase:包含所有小寫ASCII字母的字符串。
string.ascii_uppercase:包含所有大寫ASCII字母的字符串。
string.digits:包含所有數(shù)字字符的字符串。
string.hexdigits:包含所有十六進(jìn)制數(shù)字字符的字符串。
string.octdigits:包含所有八進(jìn)制數(shù)字字符的字符串。
string.punctuation:包含所有標(biāo)點(diǎn)符號(hào)的字符串。
string.whitespace:包含所有空白字符的字符串。
2、string模塊中的常用函數(shù):
string.capwords(s, sep=None):將字符串s中的每個(gè)單詞首字母大寫,其他字母小寫,如果提供了sep參數(shù),則將其視為單詞分隔符。
string.join(sequence):將序列中的元素連接成一個(gè)字符串,可以指定一個(gè)可選的分隔符,默認(rèn)為空字符串。
string.lstrip(s, chars=None):從字符串s的左側(cè)刪除指定的字符,如果沒有提供chars參數(shù),則刪除所有空白字符。
string.replace(old, new, count=1):將字符串old替換為new,如果提供了count參數(shù),則替換前count個(gè)匹配項(xiàng)。
string.split(s, sep=None, maxsplit=1):將字符串s分割成一個(gè)列表,可以指定一個(gè)可選的分隔符sep,默認(rèn)為所有的空白字符,如果提供了maxsplit參數(shù),則最多進(jìn)行maxsplit次分割。
string.strip(s, chars=None):從字符串s的兩側(cè)刪除指定的字符,如果沒有提供chars參數(shù),則刪除所有空白字符。
下面是一些示例代碼:
import string
使用string模塊中的常量
print("All ASCII letters:", string.ascii_letters)
print("All lowercase ASCII letters:", string.ascii_lowercase)
print("All uppercase ASCII letters:", string.ascii_uppercase)
print("All digits:", string.digits)
print("All hex digits:", string.hexdigits)
print("All oct digits:", string.octdigits)
print("All punctuation:", string.punctuation)
print("All whitespace:", string.whitespace)
使用string模塊中的函數(shù)
s = "hello world"
print("Original string:", s)
print("String with capwords:", string.capwords(s))
print("String with join:", string.join(s.split(), ""))
print("String with lstrip:", string.lstrip(s, "l"))
print("String with replace:", string.replace(s, "o", "0"))
print("String with split:", string.split(s, " "))
print("String with strip:", string.strip(s, "l"))
以上就是關(guān)于Python中string庫函數(shù)的用法的詳細(xì)技術(shù)教學(xué),希望對(duì)你有所幫助!
網(wǎng)站名稱:string庫函數(shù)的用法引用24個(gè)字母
標(biāo)題鏈接:http://fisionsoft.com.cn/article/djejipg.html


咨詢
建站咨詢
