简体   繁体   中英

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 ?

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.

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]

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM