John Smith
John Smith

Reputation: 73

Can I split an input that doesnt have spaces?

I'm attempting to create a program that relates to poker using python. When someone inputs "9H", is there a way to separate the 9 from the H?

Upvotes: 1

Views: 66

Answers (4)

Óscar López
Óscar López

Reputation: 236034

You can access each individual character in a string using its index, there's no need to convert the input to a list. If it's just two characters, you can always do this:

card = '9H'
number, suit = card[0], card[1]

Or even simpler, we can unpack the elements in the string:

number, suit = card

Now number will contain the string value '9' and suit will be equal to 'H'. Be careful with the edge case though - how do we process a card such as '10S'? a bit clunkier, but we can use regular expressions, and this will work for all valid inputs of cards:

import re
card = '10S'
number, suit = re.findall(r'(\d+)(\D)', card)[0]

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54213

Note that all these answers are scary if you'll be expecting input like 10H rather than TH. In which case I'd consider stripping the last token (which should always be a single character representing the suit) from the rest and doing that instead.

your_input = "10H"
rank, suit = your_input[:-1], your_input[-1]

This plays nicely for more "normal" inputs as well:

rank, suit = "9H"[:-1], "9H"[-1]

Upvotes: 0

bennettp123
bennettp123

Reputation: 419

Convert it to a list:

$ python
Python 2.7.8 (default, Oct 30 2014, 18:30:15)
>>> "example"[0]
'e'
>>> "example"[1]
'x'
>>> list("example")
['e', 'x', 'a', 'm', 'p', 'l', 'e']

Upvotes: 1

user2555451
user2555451

Reputation:

The easiest way to break a string into individual characters is to call list() on it:

>>> list("9H")
['9', 'H']
>>>

This will iterate over the string and collect its characters into a new list object.

Upvotes: 6

Related Questions