有没有办法在 Python 中按第 n 个分隔符分割字符串? [英] Is there a way to split a string by every nth separator in Python?

查看:34
本文介绍了有没有办法在 Python 中按第 n 个分隔符分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有以下字符串:

For example, if I had the following string:

这是一个字符串"

我可以按每第二个-"而不是每个-"分割它,以便它返回两个值(this-is"和a-string")而不是返回四个?

Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?

推荐答案

这是另一个解决方案:

span = 2
words = "this-is-a-string".split("-")
print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]

这篇关于有没有办法在 Python 中按第 n 个分隔符分割字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆