使用多个分隔符分割字符串

发布于 2025-01-03 10:43:36 字数 130 浏览 1 评论 0原文

我有一个包含棋子坐标的字符串:

pieces = [Ka4Qb3Td7b4c4]

如何将字符串拆分为一个列表,并用数字分隔?

想要的输出:['Ka4','Qb3','Td7','b4','c4']

I have a string which contains coordinates of chess pieces:

pieces = [Ka4Qb3Td7b4c4]

How can i split the string into a list, separated by the numbers?

Wanted output : ['Ka4', 'Qb3', 'Td7', 'b4', 'c4']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

朮生 2025-01-10 10:43:36

闻起来像家庭作业,但很容易..

import re
pieces = 'Ka4Qb3Td7b4c4'
m = re.compile('[A-Za-z]{1,2}\d+')
print m.findall(pieces)

产量..

['Ka4', 'Qb3', 'Td7', 'b4', 'c4']

Smells like homework, but easy enough..

import re
pieces = 'Ka4Qb3Td7b4c4'
m = re.compile('[A-Za-z]{1,2}\d+')
print m.findall(pieces)

Yields..

['Ka4', 'Qb3', 'Td7', 'b4', 'c4']
暖阳 2025-01-10 10:43:36

这对我有用:

import re
mylist = []
pieces = "Ka4Qb3Td7b4c4"
for chunk in re.finditer("(.*?[0-9]{1})",pieces):
    mylist.append(chunk.group(1))
print mylist

如果有两位数字分隔符,您可能需要调整正则表达式(我不是国际象棋爱好者...)

为了兴趣,我将其重新设计为建议的列表理解,并同意它更干净:

import re
pieces = "Ka4Qb3Td7b4c4"
mylist = [ chunk.group(0) for chunk in re.finditer(".*?\d+",pieces) ]
print mylist

This works for me:

import re
mylist = []
pieces = "Ka4Qb3Td7b4c4"
for chunk in re.finditer("(.*?[0-9]{1})",pieces):
    mylist.append(chunk.group(1))
print mylist

You may need to adjust the regex if there are 2 digit seperators (I'm not a chess guy...)

For interest sake, I reworked it as the suggested list comprehension and agree it's much cleaner:

import re
pieces = "Ka4Qb3Td7b4c4"
mylist = [ chunk.group(0) for chunk in re.finditer(".*?\d+",pieces) ]
print mylist
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文