1

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']

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

5 Comments

I'm not going to not post because I think it's homework.. Especially if the proposed solution in the question is poorly suited for the task. How can you expect people to learn if you don't help them?
Your answer is just code. You could explain how to split the string using regular expressions. That would be far more useful. See meta.stackexchange.com/a/10812/147331 for more detailed reasoning.
It's always a tough call trying to figure out what depth one should go into when answering a question - generally when I see folks who're 500+ rep I tend to be a bit more brief letting the code talk for itself. If they're sub-100 I'll go into a bit more detail. I do appreciate the feedback though - food for thought.
The "tough call" is an excuse for "take too long, others answer first and get the points". So, it is a mater of being after the points, or wanting to write a great answer, that may not get so much upvotes because its late. Unfortunately stackexchange's voting system cant work around our own greed, we have to admit it.
Actually - the truth is, I play a game every day for about 15-30 minutes. I just try to, as fast as possible answer as many questions correctly as I can - kind of a 'lightning round'. Not really for the points, just for the fun of it. I don't know why anyone would 'game' the system anyway. Points can't be redeemed for anything, they have no intrinsic value. My co-workers don't use stack overflow and wouldn't be impressed with my score if they did. It's just a bit of fun. More challenging than playing a video game, less challenging than doing the work I procrastinate on for my 15-30 minutes..
2

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

1 Comment

this would look really nice with a list comprehension

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.