简体   繁体   English

使用 PyInputPlus 将字符串限制为特定长度并仅允许某些字符

[英]Using PyInputPlus to restrict a string to specific length and allow only certain characters

how do I use PyInputPlus to restrict input length and it's allowed characters.我如何使用 PyInputPlus 来限制输入长度及其允许的字符。 I did some research and found this question , but this question doesn't have answer specifically for PyInputPlus.我做了一些研究并发现了这个问题,但是这个问题没有专门针对 PyInputPlus 的答案。 And I want to allow both 'az' and 'A-Z'.我想同时允许 'az' 和 'A-Z'。

Code so far:到目前为止的代码:

import pyinputplus as pyip
oneLetter = pyip.inputStr(prompt=':')
if not re.match("^[a-z]*$", letter):
   print ("Error! Only letters a-z allowed!")
if len(letter)>1:
   print('You can only type in 1 character')
else:
   print(oneLetter)

Desire output:期望输出:

:1
>Only letters a-z, A-Z allowed
:Bob
>Only 1 letter allowed
:B
>B

You may try the code below to fix your issue.您可以尝试下面的代码来解决您的问题。 I would suggest getting more familiar with regular expressions.我建议更熟悉正则表达式。

import pyinputplus as pyip
import regex as re

oneLetter = pyip.inputStr(prompt=':')
if len(oneLetter) > 1:
   print('You can only type in 1 character')
elif not re.match("^[a-zA-Z]$", oneLetter):
   print ("Error! Only letters a-z allowed!")
else:
   print(oneLetter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 只允许某些字符 - Only allow certain characters 如何在 Python 中的字符串中只允许数字、字母和某些字符? - How to only allow digits, letters, and certain characters in a string in Python? 使用Python只保留字符串中的某些字符? - Keeping only certain characters in a string using Python? 使用 python 仅从字符串中拆分和解析特定字符 - Split and parse only specific characters from string using python 在文本文件中查找包含特定字符且具有特定长度的单词 - find a word within a text file that contains certain characters and is a specific length SQL SELECT,其中单元格为一定长度并包含特定字符 - SQL SELECT where cell is a certain length and includes specific characters 如果两个字符串的长度不相同,如何仅使用核心 python 3 一个接一个地连接字符串字符 - How to join string characters one by one if both string are not same in length using core python 3 only 使用 python 仅解析字符串中的特定字符 - Parse only specific characters from the string using python 如果某些字符不在字符串中的特定位置,则删除它们#python - Remove certain characters if they are not in a specific location in a string #python 在python中的列表中解析以某些字符开头且长度为N的字符串 - Parse through list in python for string that starts with certain characters and is length N
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM