Python_去除字符串中的空格

作者:Gakki

01. strip() 方法

  • strip() :用于移除字符串头尾指定的字符(默认为空格)或字符序列。
    注: 该方法只能删除开头或结尾的字符,不能删除中间部分的字符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.strip()
old_data2 = "com.123fa.comsfasf.comasdfrs324.com"
new_data2 = old_data2.strip(".com")
print(new_data)
print(new_data2)
  • 输出结果:
a b c d 1 1 3 1
123fa.comsfasf.comasdfrs324

02. lstrip()方法

  • lstrip():用于截掉字符串左边的空格或指定字符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.lstrip()
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.lstrip("com")
print(new_data)
print(new_data2)
  • 输出结果:
a b c d 1 1 3 1 
.123fasfasf asdfrs324.com

03. rstrip()方法

  • rstrip():用于删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.rstrip()
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.rstrip("com")
print(new_data)
print(new_data2)
  • 输出结果:
 a b c d 1 1 3 1
com.123fasfasf asdfrs324.

04. replace()方法

  • replace():把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
  • 语法:str.replace(old, new[, max])
old_data = " a b c d 1 1 3 1 "
new_data = old_data.replace(" ","")
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.replace("a", "A", 2)
print(new_data)
print(new_data2)
  • 输出结果:
abcd1131
com.123fAsfAsf asdfrs324.com

05. join()方法 + split()方法

  • split():通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。
  • 语法:str.split(str="", num=string.count(str))
  • join():用于将序列中的元素以指定的字符连接生成一个新的字符串。
old_data = " a b c d 1 1 3 1 "
# 1.将字符串按空格分割成列表
new_data = old_data.split()
print(new_data)
# 2.使用join()将列表内容拼接成新的字符串
new_data = "".join(new_data)
print(new_data)
  • 输出结果:
['a', 'b', 'c', 'd', '1', '1', '3', '1']
abcd1131

06. 使用正则表达式

import re
old_data = " a b c d 1 1 3 1 "
# 去掉空格
new_data = re.sub(r"\s+", "", old_data)
old_data2 = "com.123fa.com sfasf.com asdfrs324.com"
# 将 com 替换为 www
new_data2 = re.sub(r"com", "www", old_data2)
print(new_data)
print(new_data2)
  • 输出结果:
abcd1131
www.123fa.www sfasf.www asdfrs324.www
  • sub函数:将整个字符串用新的字符串替换掉。
  • \s:匹配各种不同的空白符,如:空格、制表符、回车等。等价于 [\t\n\r\f]。
不足之处,欢迎留言补充!!!

你可能感兴趣的:(Python_去除字符串中的空格)