Issue
Question: Write a program that prints this sentence with only alphabets and spaces without using built-in string methods. You can use
ord()
andchr()
to solve this question.
Expected Input/Output
Enter a sentence: I’m 9 years old.
>>> Im years old
My Codes
phrase = "I'm 9 years old."
result = ''
for i in phrase:
if i == 9:
result = ord(i) + ord(23)
elif i == "'":
result = ord(i) - ord(7)
print(result)
My Output
TypeError: ord() expected string of length 1, but int found
I tried to identify the problem and fix my codes, but I tried different ways and didn't get the right codes anyway, so I would like some tips and help on solving this question!
Solution
Here's an answer that doesn't use any string methods like isalpha()
or replace()
.
phrase = "I'm 9 years old."
result = ""
for i in phrase:
if i in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ":
result += i
print(result)
This answer just checks if the character is in a string of allowed characters before adding it to the result.
ord()
makes the code less clear IMO, but if your teacher wants you to use it you could do this:
phrase = "I'm 9 years old."
result = ""
for i in phrase:
if 123 > ord(i) > 96 or 91 > ord(i) > 64 or ord(i) == 32:
result += i
print(result)
This answer checks if the character's ASCII code corresponds to an alphabetic character or a space.
Answered By - exciteabletom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.