Click here to Skip to main content
15,887,361 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to limit the input. The user can enter a letter (a-h) and an integer (1-8) for example c4 (chess board) How can I do it?
This is my code:


What I have tried:

square  = input("Enter a chess square identifier : ") 

if (ord(square[0]))%2 != int(square [1])%2:

    print("white")
else:
    print( "black")
Posted
Updated 3-Sep-21 9:40am

One way to validate the input is to use regular expression. Have a look at re — Regular expression operations — Python 3.9.7 documentation[^] and https://pythonspot.com/regular-expressions/[^]

What comes to the regular expression itself, you can read more from Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns[^]. In this case the expression could look something like
^[a-h]{1}[1-8]{1}$

Just remember to use IGNORECASE with re.
 
Share this answer
 
Comments
Patrice T 3-Sep-21 15:59pm    
I think you can simplify to "^[a-h][1-8]$"
Wendelius 4-Sep-21 0:05am    
Yes, one is the default quantifier so it's not mandatory to include it.
Quote:
I would like to limit the input. The user can enter a letter (a-h) and an integer (1-8) for example c4 (chess board) How can I do it?

smells like pattern matching. Ever thought of Regular Expressions ?
this will match a letter followed with a digit: [abcdefgh][12345678]

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900