python字符串长度,将Python输入字符串限制为某些字符和长度

I just started learning my first real programming language, Python. I'd like to know how to constrain user input in a raw_input to certain characters and to a certain length. For example, I'd like to show an error message if the user inputs a string that contains anything except the letters a-z, and I'd like to show one of the user inputs more than 15 characters.

The first one seems like something I could do with regular expressions, which I know a little of because I've used them in Javascript things, but I'm not sure how to use them in Python. The second one, I'm not sure how to approach it. Can anyone help?

解决方案

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")

if not re.match("^[a-z]*$", input_str):

print "Error! Only letters a-z allowed!"

sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")

if len(input_str) > 15:

print "Error! Only 15 characters allowed!"

sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")

if not re.match("^[a-z]*$", input_str):

print "Error! Only letters a-z allowed!"

sys.exit()

elif len(input_str) > 15:

print "Error! Only 15 characters allowed!"

sys.exit()

print "Your input was:", input_str

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值