Python-5-字符串方法
生活随笔
收集整理的這篇文章主要介紹了
Python-5-字符串方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
center >>> "The Middle by Jimmy Eat World".center(39) ' ?? ?The Middle by Jimmy Eat World ?? ?' >>> "The Middle by Jimmy Eat World".center(39, "*") '*****The Middle by Jimmy Eat World*****' find 在字符串中查找子串,找到返回子串第一個(gè)字符索引,否則返回- >>> 'With a moo-moo here, and a moo-moo there'.find('moo') 7 >>> title = "Monty Python's Flying Circus" >>> title = "Monty Python's Flying Circus" >>> title.find('Monty') 0 >>> title.find('Zirquss') -1 成員資格檢查in智能用于單個(gè)字符,而這個(gè)可以多個(gè) 可以指定起點(diǎn)和終點(diǎn) >>> subject = '$$$ Get rich now!!! $$$' >>> subject.find('$$$') 0 >>> subject.find('$$$', 1) # 只指定了起點(diǎn) 20 >>> subject.find('!!!') 16 >>> subject.find('!!!', 0, 16) # 同時(shí)指定了起點(diǎn)和終點(diǎn) -1 起點(diǎn)和終點(diǎn)值指定的范圍包含起點(diǎn)不包含終點(diǎn),這是python的慣用做法 join 與split相反 >>> seq = [1, 2, 3, 4, 5] >>> sep = '+' >>> sep.join(seq) # 嘗試合并一個(gè)數(shù)字列表 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: sequence item 0: expected string, int found >>> seq = ['1', '2', '3', '4', '5'] >>> sep.join(seq) # 合并一個(gè)字符串列表 '1+2+3+4+5' >>> dirs = '', 'usr', 'bin', 'env' >>> '/'.join(dirs) '/usr/bin/env' >>> print('C:' + '\\'.join(dirs)) C:\usr\bin\env lower 返回小寫(xiě)版本 >>> 'Trondheim Hammer Dance'.lower() 'trondheim hammer dance' title 所有單詞首字母大寫(xiě) >>> "that's all folks".title() "That'S All, Folks" replace 將指定子串都替換為另一個(gè)字符串,并返回替換后的結(jié)果 >>> 'This is a test'.replace('is', 'eez') 'Theez eez a test' split 與join相反,將字符串拆分為序列 >>> '1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5'] >>> '/usr/bin/env'.split('/') ['', 'usr', 'bin', 'env'] >>> 'Using the default'.split() ['Using', 'the', 'default'] strip 將字符串的開(kāi)頭和末尾的空白刪除,并返回刪除后的結(jié)果 >>> ' internal whitespace is kept '.strip() 'internal whitespace is kept' translate 使用前要先創(chuàng)建一個(gè)轉(zhuǎn)換表 >>> table = str.maketrans('cs', 'kz') 兩個(gè)參數(shù)為兩個(gè)長(zhǎng)度相同的字符串,指定將第一個(gè)字符串中的每個(gè)字符都替換為第二個(gè)字符串中相應(yīng)的字符 內(nèi)部存儲(chǔ)為unicode >>> table {115: 122, 99: 107} >>> 'this is an incredible test'.translate(table) 'thiz iz an inkredible tezt' 第三個(gè)參數(shù)為指定要將那些字母刪除 >>> table = str.maketrans('cs', 'kz', ' ') >>> 'this is an incredible test'.translate(table) 'thizizaninkredibletezt' 判斷字符串是否滿(mǎn)足特定條件 是true,否則false isalnum、 isalpha、 isdecimal、 isdigit、 isidentifier、 islower、 isnumeric、isprintable、 isspace、 istitle、 isupper
轉(zhuǎn)載于:https://www.cnblogs.com/swefii/p/10795504.html
總結(jié)
以上是生活随笔為你收集整理的Python-5-字符串方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Django学习之数据库与ORM
- 下一篇: linux操作python