Python3 去除空格


1 去除兩端空格(strip())

a.去除左端空格 lstrip()

str0='abcdef'
str1='  abcdef'
print(str0)
print(str1.lstrip())

b.去除右端空格 rstrip()

str0='abcdef  '
str1='abcdef  '
print(str0)
print(str1.rstrip())

c.去除兩端空格 strip()

str0='  abcdef  '
str1='  abcdef  '
print(str0)
print(str1.strip())

2 空格替換(replace() 推薦使用)

str0='  a b c d e f  '
str1='  a b c d e f  '
print(str0)
print(str1.replace(' ',''))

3 重新組合替換空格(使用split分割字符,使用join重新組合,效率低)

str0='  a b c d e f  '
str1='  a b c d e f  '
print(str0)
print(''.join(str1.split()))

4 正則表達式去空格(用sub()方法替換)

import re
str0='  a b c d e f  '
str1='  a b c d e f  '
print(str0)print(re.sub(' ','',str1))

[1] https://www.cnblogs.com/146xwq/p/9684891.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM