python | strip(), split()的区别

strip(), split()的区别

这是我总是在混淆使用的点,究其原因,我想可能是混淆了两者的翻译,从而对它们的使用也经常乱用一通。

strip:剥去,剥夺;to remove something that covers something

split:劈开,分离;to divide into smaller groups

split:

method split takes the separator character(s) as a string argument, and returns the contents of the target string as a list of strings, separated at the separator.

split方法将分隔符作为字符串参数,并将目标字符串的内容作为字符串列表返回,并在分割符处分割。

上面这话读起来总觉得拗口,现在以同一句话为例讲split的不同用法,就能明白:

  1. split()

    string = "Little do you know, how I'm breaking while you fall asleep; I will be alright."
    a = string.split()
    print(a)
    # ['Little', 'do', 'you', 'know,', 'how', "I'm", 'breaking', 'while', 'you', 'fall', 'asleep;', 'I', 'will', 'be', 'alright.']
    
  2. split(",")

    string = "Little do you know, how I'm breaking while you fall asleep."
    a = string.split(",")
    print(a)
    # ['Little do you know', " how I'm breaking while you fall asleep; I will be alright."]
    

不难看出,split就是把括号中的符号视为分割标志,当遇到这个符号时,就自动切一刀,把字符串分为两个部分,并且以list的形式返回。

另外,split()split(" ")的效果相同。

strip:

strip removes all spaces, line breaks, tabs and other characters which would not normally be printed out,from the beginning and end of a string.

这个很好理解,就是strip会移除字符串开头和结尾的spaces、tabs等等。

string = "    To see a world in a grain of sand "
b = string.strip()
print(b)
# To see a world in a grain of sand 

strip括号内通常不加东西,而且它的作用部位限于字符串的开头和结尾。如果只想单独移除开头的,可以使用lstrip.(),单独移除结尾的,可以使用rstrip.()

综上,这两个其实压根没有相同之处,希望之后也不会再出错了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值