python-基础语法-使用strip()和split()处理空白字符

本文介绍了Python中处理空白字符的方法,重点讲解了strip()和split()函数的用法。strip()用于移除字符串头尾的空白字符,split()则通过指定分隔符对字符串进行切片,可用于数据清洗。
部署运行你感兴趣的模型镜像

0.摘要

在数据输入的时候,考虑的易读性,往往会加上大量的空白字符调整间距。但在使用数据时候,需要恰当地处理掉空白字符。

本文主要介绍,使用sprip()和split()处理空白字符的方法。

 

1.String strip()方法

官方解释:

    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.

翻译:

若chars为未给定,则删除字符串头尾的空白字符,包括\r,\t\,\n和空格;

若chars给定,则删除字符串头尾,位于chars中的字符。注意,无顺序要求。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

str1 = '\n\n\r\t   hello,world!  \t  '
print(str1.strip())
#result:hello,world!

str2 = "1024 grams potato convert to Calories is equel to 2048"
print(str2.strip('0123456789'))
#result: grams potato convert to Calories is equel to

str3 = "1024 grams potato convert to Calories is equel to 2048"
print(str3.strip('0123456789 '))
#result:grams potato convert to Calories is equel to

注意,这里str2和str3的处理方式有细微差别:

str2.strip('0123456789')中没有包含空格字符;
str3.strip('0123456789 ')中包含了空格字符;

所以,在最后的输出中,str3处理了空格字符,而str2没有;

另外,strip()方法还有两个变体:

S.lstrip(chars)       删除s字符串中开头处,位于 chars删除序列的字符

S.rstrip(chars)      删除s字符串中结尾处,位于 chars删除序列的字符

 

2.String split()方法

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串.

S.split(sep=None, maxsplit=-1) -> list of strings
  • sep -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • maxsplit -- 分割次数。
s = 'string1 string2  string3  \n string4'
print(s.split())
print(s.split(' '))
print(s.split(sep=None,maxsplit=3))

结果:

注意,如果指定了sep为一个空格,那么split()将只按照一个空格进行分割。

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值