1

I'm in the really early stages of learning how to program, and my teacher is only referring to the internet for help. I've tried to search for the answer for hours now, but can't seem to find anything. Here goes:

I want the user to input a string which can only contain one %-sign, and only accept three characters before that, for example:

hey%areyoustillout

can be accepted, but

oh%Ithoughyouwenthome%%

should deliver an error message.

This is how far I've coded:

message = input('Message')

if message == '%':
    print('Valid message')

else:
    print('Invalid message')

This only accept the message when the message is solely '%'. What command or condition should I use to tell the program that % can be AMONG the input string? I've tried to interpret this but I can't get it to work.

I understand this probably is a very basic question and I'm sorry if I bother you with a stupid question. Many thanks in advance.

Noah
  • 430
  • 1
  • 4
  • 21
SpaceBar
  • 11
  • 2

1 Answers1

1

You can use regular expressions. For instance, if you want to match 3 characters, then %, then anything after, you can use ^\w{3}\%.

The ^ means start of the string, \w means any "word" character, the {3} means match 3 of the preceding thing, and then \% obviously means find the %. So this will check if the string starts with 3 characters then a %.

import re
message = input('Message')

if re.match('^\w{3}\%', message):
    print('Valid message')
else:
    print('Invalid message')

If you want to learn more you can use this website: https://regexr.com/

Dan Ruswick
  • 2,990
  • 2
  • 12
  • 14