Python3 —— 字符串分割

s.split([sep, [maxsplit]]) 以sep是分隔符,把s分割成一个list。sep默认为空格。maxsplit是分割的次数,默认是对整个s进行分割

str = 'This is a string. We want to split it!'
# 从前向后分割
str.split()
str.split(' ', 3)
str.split('s')

结果:
['This', 'is', 'a', 'string.', 'We', 'want', 'to', 'split', 'it!']

['This', 'is', 'a', 'string. We want to split it!']

['Thi', ' i', ' a ', 'tring. We want to ', 'plit it!']


s.rsplit([sep, [maxsplit]]) 和split()的区别是它是从s的串尾往前进行分割。

str = 'This is a string. We want to split it!'
# 从后向前分割
str.rsplit()
str.rsplit(' ', 3)
str.rsplit('s')

结果:
['This', 'is', 'a', 'string.', 'We', 'want', 'to', 'split', 'it!']

['This is a string. We want', 'to', 'split', 'it!']

['Thi', ' i', ' a ', 'tring. We want to ', 'plit it!']

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中有多种字符串处理方法。下面是几种常见的字符串处理方法: 1. 去掉头尾空格:可以使用strip()方法。strip()方法用于去除字符串开头和结尾的空白符,包括换行、回车、制表符和空格。例如,对于字符串" hello python ",使用st.strip()将去除头尾的空格,得到"hello python"。 2. 去掉头部空格:可以使用lstrip()方法。lstrip()方法用于去除字符串开头的字符和空白符。例如,对于字符串" hello python ",使用st.lstrip()将去除开头的空格,得到"hello python"。 3. 去掉尾部空格:可以使用rstrip()方法。rstrip()方法用于去除字符串结尾的字符和空白符。例如,对于字符串" hello python ",使用st.rstrip()将去除结尾的空格,得到"hello python"。 4. 字符串替换:可以使用replace()方法。replace()方法可以将字符串中的旧字符串替换为新字符串。如果指定第三个参数,可以限制替换的次数。例如,对于字符串" hello python ",使用st.replace('python', 'word')将把"python"替换为"word",得到"hello word"。 5. 字符串切片:可以使用split()方法。split()方法可以按照指定的分隔符将字符串分割成多个子字符串,并返回一个子字符串列表。例如,对于字符串"What's your name?",可以使用st.split(' ')将其切分成多个子字符串,得到["What's", "your", "name?"]。 这些是一些常见的字符串处理方法,可以帮助你在Python中对字符串进行各种操作和处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [python教程:15种字符串操作方法](https://blog.csdn.net/qdPython/article/details/124063345)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Python——字符串处理](https://blog.csdn.net/JD20200906/article/details/125872342)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值