python stringstrip方法详解_python-基础语法-使用strip()和split()处理空白字符

0.摘要html

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

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

1.String strip()方法翻译

官方解释:code

S.strip([chars]) -> strhtm

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.blog

翻译:ip

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

若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没有;

3f734afb242740f45468785a312bb049.png

另外,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))

结果:

4fe5a5e2538aa63aa1ae8aa6f0af8a4d.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值