python字符串与文本处理技巧(3):字符剔除、字符对齐、字符拼接、字符插入变量
1.?刪除字符串中不需要的字符
去掉文本字符串開(kāi)頭,結(jié)尾或者中間不想要的字符,比如空白。
- strip() & Istrip() & rstrip()
strip() 方法能用于刪除開(kāi)始或結(jié)尾的字符。 lstrip() 和 rstrip() 分別從左和從右執(zhí)行刪除操作。 默認(rèn)情況下,這些方法會(huì)去除空白字符,也可以指定其他字符。
s = ' hello world \n' print(s.strip()) # >>> hello world print(s.lstrip()) # >>> hello world \n print(s.rstrip()) # >>> hello world ss = '-----hello=====' print(ss.strip('-')) # >>> hello===== print(ss.strip('=')) # >>> -----hello print(ss.strip('-=')) # >>> hello- replace() & re.sub()
這些 strip() 方法在讀取和清理數(shù)據(jù)以備后續(xù)處理的時(shí)候是經(jīng)常會(huì)被用到的。默認(rèn)情況下strip()方法僅對(duì)字符串開(kāi)頭的空格有用。?這種去除操作不會(huì)對(duì)字符串的中間的文本(指的是空格)產(chǎn)生任何影響。如果為我們想處理字符串中間的空格,那么需要求助其他技術(shù)。比如使用replace()方法或者是用正則表達(dá)式替換。示例如下:比如:
import res = ' hello world \n' print(s.strip()) # >>> hello world print(s.replace(' ','')) # >>> helloworld print(re.sub('\s+', ' ', s)) # >>> hello world2.?字符串對(duì)齊
- ljust() & rjust()?& center()
對(duì)于基本的字符串對(duì)齊操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。
s = 'hello world' print(s.ljust(20)) # >>> 'hello world ' print(s.rjust(20)) # >>> ' hello world' print(s.center(20)) # >>> ' hello world 'print(s.ljust(20,'*')) # >>> hello world********* print(s.rjust(20,'*')) # >>> *********hello world print(s.center(20,'*')) # >>> ****hello world*****- format()
format() 函數(shù)的一個(gè)好處是它不僅適用于字符串。還可以用來(lái)格式化任何值。 比如,用它來(lái)格式化數(shù)字:
x = 3.1415926 print(format(x, '*>10')) # >>> *3.1415926 print(format(x, '*>10.2f')) # >>> ******3.143. 字符串拼接
將幾個(gè)小型字符串拼接成一個(gè)較大的字符串。
- join()
這種語(yǔ)法看上去會(huì)比較怪,但是join()被指定為字符串的一個(gè)方法。 這樣做的部分原因是想去連接的對(duì)象可能來(lái)自各種不同的數(shù)據(jù)序列(比如列表,元組,字典,文件,集合或生成器等), 如果在所有這些對(duì)象上都定義一個(gè)join()方法明顯是冗余的。
如果僅僅只是合并少數(shù)幾個(gè)字符串,使用加號(hào)(+)通常已經(jīng)足夠了:
4. 字符串中插入變量
很多時(shí)候我們需要?jiǎng)?chuàng)建一個(gè)內(nèi)嵌變量的字符串,變量被它的值所表示的字符串替換掉。
- format()
Python并沒(méi)有對(duì)在字符串中簡(jiǎn)單替換變量值提供直接的支持。 但是通過(guò)使用字符串的format()方法來(lái)解決這個(gè)問(wèn)題。比如:
- format_map() & vars() /// 變量域
或者,如果要被替換的變量能在變量域中找到, 那么我們可以結(jié)合使用format_map()?和?vars()?。例如:
s = '{appName} has {n} messages' appName = 'QQ' n = 50 s__ = s.format_map(vars()) print(s__) # >>> QQ has 50 messagesvars()還有一個(gè)有意思的特性就是它也適用于對(duì)象實(shí)例。比如:
s = '{name} has {n} messages' class Info:def __init__(self, name, n):self.name = nameself.n = na = Info('Wesee', 50) print(s.format_map(vars(a))) # >>> Wesee has 50 messagesComment :?format 和 format_map() 的一個(gè)缺陷就是它們并不能很好的處理變量缺失的情況,比如:
s.format(name='Wesee') >>> Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'n'本博文參考《python3-codebook》
總結(jié)
以上是生活随笔為你收集整理的python字符串与文本处理技巧(3):字符剔除、字符对齐、字符拼接、字符插入变量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Google存储海量私人信息 隐私问题不
- 下一篇: 几个小时后,我学数据库,找到一些代码