Write a python function called strToAscii with a parameter called message that returns the ASCII code equivalent of each character in the string represented by message and in the same order of appearance. For example, a partial ASCII table is provided below. Character ASCII 'a' 97 'b' 98 'c' 99 'd' 100 A call to strToAscii('abdc') will result in, >>>print(strToAscii('abdc')) 979810099 >>>print(strToAscii('ccad')) 999997100 Requirements and hints: (1) use local variable ascii_str for the desired computational result (resulted string) (2) argument should message, which is a string (3) use loop (4) use function ord(ch), which return the ASCII value of a character, e.g, ord('a') will be 97
时间: 2024-03-11 11:48:27 浏览: 13
Certainly! Here's the code for the `strToAscii` function that meets all the requirements you specified:
```
def strToAscii(message):
ascii_str = ""
for ch in message:
ascii_str += str(ord(ch))
return ascii_str
```
To explain the code a bit: we first initialize a local variable `ascii_str` to an empty string. We will use this string to build up the ASCII code equivalent of the input string.
We then use a `for` loop to iterate over each character `ch` in the input `message` string. For each character, we use the `ord` function to obtain its ASCII code value, which we then convert to a string using the `str` function. We then append this string to the `ascii_str` variable.
Finally, we return the `ascii_str` variable, which will contain the ASCII code equivalent of the input string.
You can call this function with a string argument like so:
```
print(strToAscii('abdc')) # prints 979810099
print(strToAscii('ccad')) # prints 999997100
```
Let me know if you have any other questions!