How would I write a Python program that inputs a string of characters which represent a vanity telephone number, e.g., 800-MYPYTHON, and prints the all numeric equivalent, 800-69798466. You should implement this using a loop construct to process each character from left to right. Build a new string that is the all numeric equivalent and then print the string.
Responses (1)
That's not a question, that's homework, and as such I'll provide insights rather than code. Bear in mind there's more of it here than the immediate requirement.
First, I don't know if it's common knowledge (we don't have vanity numbers here), but the goal is to translate (abc) -> 2, (def) ->3, ..., (wxyz) -> 9.
This could be done efficiently & elegantly in a two liner using translate or dictionary - one of python's points of strength is all these handy little functions; you should have a look at it even if irrelevant for the task.
www.tutorialspoint.com/python/string_translate.htm
Now, for the loop method, you should take into consideration the fact that python is inefficient with string operations, so the best thing to do is loop over the string, convert the character to a value, either using a set of if conditions or a dictionary, add it to a list, and finally do a join on the list - ''.join(list1).
If not permitted to use join, simply add (+) the new number char to a single string instead - this will perform the concatenation, albeit inefficiently as stated.
If you don't know how to do loops, conditions etc, look it up.