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