Reputation: 1
I was doing some practice tasks from NiO for an upcoming coding competition. The competition is held online and forces me to use stdin.readline so they can test my code. The usage of stdin got me really stuck. The script is running flawlessly with raw_input but throws "ValueError: substring not found" whenever I switch to sys.stdin.readline. Am I doing something stupidly wrong?
import string
import sys
n = int(sys.stdin.readline())
txt = sys.stdin.readline()
ab = string.ascii_uppercase
result = ""
for letter in txt:
result += ab[((ab.index(letter) + n) % 26)]
print result
Upvotes: 0
Views: 474
Reputation: 114230
The fundamental flaw with your code is that you do not sanitize your input and you are getting an illegal character (\n
) at the end. The operation ab.index(...)
assumes that all inputs are uppercase letters, so it fails when they are not.
You can fix this in a couple of ways. One is to convert everything that can be converted to uppercase to uppercase and leave the rest in as-is:
import string, sys
ab = string.ascii_uppercase
n = int(sys.stdin.readline())
txt = sys.stdin.readline()
result = [ab[(ab.index(letter.upper()) % n) % 26] for letter in txt if letter.isalpha() else letter]
Alternatively, you can just throw away all the non-uppercase inputs:
import string, sys
ab = string.ascii_uppercase
n = int(sys.stdin.readline())
txt = sys.stdin.readline()
result = [ab[(ab.index(letter) % n) % 26] for letter in txt if letter.isupper()]
There are any number of combinations of these methods you could use.
By the way, if you are interested in having a prompt for your input, use print
with end=''
:
print('How far to shift? ', end='')
n = int(sys.stdin.readline())
print('Text to encode? ', end='')
txt = sys.stdin.readline()
...
Upvotes: 1
Reputation: 336118
readline()
will return the entire line, including the newline character at the end. Since \n
isn't present in ascii_uppercase
, you're getting the error.
Use txt = sys.stdin.readline().strip()
and the error should go away.
Upvotes: 2