Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nichole "Nikki" Carnesi
7,103 PointsHelp me understand the process...
Hi, so I'm fairly new to this coding thing and I am currently on the Python track. I love it and some things I am grasping rather quickly while other things not so quickly. I picked up a book to supplement what I am learning via the videos, because sometimes I think some things are glossed over. I am currently reading Python Programming: An Introduction to Computer Science by John Zelle. It's really been helping. Right now I am reading the chapter on Strings, Lists, and Files. We did a little exercise where we take a Unicode-encoded message and have it convert to a string of text. I tried out the program and it worked well. What I need help on, is how exactly is it working. Here's the entire code:
def main():
print("This program converts a sequence of of Unicode numbers into")
print("the string of text that it represents.\n")
inString = input("Please enter the Unicode-encoded message: ")
message = ""
for numStr in inString.split():
codeNum = int(numStr)
message = message + chr(codeNum)
print("\nThe decoded message is:", message)
main()
Now I understand the input part, and I understand how the string is split. But I am a little lost once I get to this part:
codeNum = int(numStr)
message = message + chr(codeNum)
Can anyone break it down for me please? :)
3 Answers
Mike Wagner
23,888 PointscodeNum = int(numStr) takes the string character numStr and type casts it as an int, storing it as codeNum. This is needed because chr() needs an int as described here in the documentation. Then it concatenates the returned value from chr() back into a string message. Since you're in a loop, it does this for each character in the original input, message which you print at the end of the loop's completion
james south
Front End Web Development Techdegree Graduate 33,271 Pointsthe first line calls the int cast method to strip off leading zeros, if any. the second line concatenates the result string message with a character cast of the integer. the chr method returns a string representing the character whose unicode code is the integer given as the argument to chr(). so for instance "110 105 107 107 105" is nikki.
Nichole "Nikki" Carnesi
7,103 PointsThank you James South and M Wagner, between the both of you I understand it better. Light bulb moment. :)