Home > other >  Python: How to replace strings using ord() and chr() functions instead of built-in string functions?
Python: How to replace strings using ord() and chr() functions instead of built-in string functions?

Time:07-14

Question: Write a program that prints this sentence with only alphabets and spaces without using built-in string methods. You can use ord() and chr() 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!

CodePudding user response:

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.

  • Related