Reputation: 11
char = str(input())
char1 = ord(char) + 1
print(chr(char1))
if char == "Z":
print("A")
this is the code i have written when i input Z it comes up with [ A i dont understand where this square bracket comes can you please explain why this appears and what i could do to fix it thanks
Upvotes: 1
Views: 62
Reputation: 2133
If you want a slightly more elegant and flexible solution that avoids if
conditions, you can pre-define the range of characters you want to cycle through and use the modulo operator %
so your +1
automatically cycles through an ASCII range without falling out to the [
, which is the character after Z
.
chr_range_start = ord('A') # Set your first character
chr_range_end = ord('Z') # Set your last character
chr_range = chr_range_end - chr_range_start
char = str(input())
char1 = chr_range_start + ((ord(char) + 1 - chr_range_start) % (chr_range + 1))
print(chr(char1))
If you decided you wanted to cycle through the lowercase a-z instead of A-Z, you can simply replace 'A' with 'a' and 'Z' with 'z' in the first two lines. You could do this for any range of ASCII characters.
If you wanted to change your step to +2 characters, you simply change the first +1 (the second must remain as is):
char1 = chr_range_start + ((ord(char) + 2 - chr_range_start) % (chr_range + 1))
This would give you A
→C
and Z
→Β
. If you did this with an if
condition, you'd have to change it to:
if char == 'Y':
char1 = 'A'
elif char == 'Z':
char1 = 'B'
This can become cumbersome. With the above code, you can arbitrarily change your range as well as your step value without changing code.
Upvotes: 0
Reputation: 69755
You are missing to convert to chr
after adding 1, and you can take advantage of the ternary operator in Python:
char = input() # you don't need to convert to str, input returns a string
print("A" if char == "Z" else chr(ord(char) + 1))
Syntax:
true_val if condition else false_val
condition
: A boolean expression that evaluates to either True
or False
.true_val
: A value to be assigned if the expression is evaluated to True
.false_val
: A value to be assigned if the expression is evaluated to False
.Upvotes: 0
Reputation: 1295
The issue lies in that the line print(chr(char1))
will execute even if char == "Z"
because it's not in an else
block. The square bracket arises from the fact that [
is the next ASCII character after Z
. One way to fix your code would be to write the following:
char = str(input())
char1 = ord(char) + 1
if char == "Z":
print("A")
else:
print(chr(char1))
Upvotes: 1