Thursday, June 14

Learning Python 3: String&Tuples

Short one. Strings and tuples.

1. String

Backslash is used to escape some characters like newline, tab or single quote. Such mechanism could be turned off by adding letter r before your string. Double quote and single quote here are really doing the same thing, to create a string.

Most of us use triple quote to write long comment. But triple quote is really used to create a multi-line string. Therefore, when you write down a comment using triple quote, although it would be ignored during execution, you actually create a string object in the environment.

You thought a dynamic language like Python would something like automatically converting one of those two variable in the operation "43" + 9, no; Python is very strict on type actually. Although sometimes there are scenes like using + to concatenate strings, but that are also type-stricted, but in a higher level. So in Python, built-in data types are actually classified once more into three major categories:

Numbers: Support addition, multiplication, etc. 
Sequences: Support indexing, slicing, concatenation, etc. 
Mappings: Support indexing by key, etc. 
Now it becomes clear, all types in Sequence category, list, string, support those operations. Turns out this strictness on type is actually a major characteristic of Python.

Since string is immutable, to change it you have to use methods like slicing, concatenation or method replace.  Or you could turn string into list (list), change it, then convert it back (str).

2. Tuple

Tuple is created, partly because the creator of Python believes this is a valid math model, partly because we want a immutable list. Yes, tuple acts just like list. Only one thing, it is created by () instead of [].


========
I feel this process is great. I learn some basic stuff while not waste time on things I already know. Also because of being somehow familiar with Python, I find reading is not a tedious thing for this book. However today I come across this question about how to level up from an apprentice to a guru in python in stack overflow. It offers several good ways to advance in Python, which I think I would possibly choose one or two to do in the future when I also done this book.

No comments:

Post a Comment