Rabu, 09 April 2014

Tutorial: Python Strings Literal

I feel like writing programming tutorial right now. :D. Back in the college, I always wrote programming tutorials for other people's blog and I think is was fun. Even though my writings back there was awful because I only cover basic knowledge of a programming language. So, right now, I want to write more conceptual tutorial that I hope would make the reader more keen about programming. I will start with the String literals.


Kinds of String Literals

Python has three kinds of string literals single quoted, double quoted, and triple quoted. All types of Python strings are immutable. It means, every operation that tried to change the content of the string will resulted in a new string object. It is different with Ruby string that is mutable.  Here are the examples of the usage.
    
    print 'hello world!'
    print "hello world!"
    print """hello world!"""

Those three statements will return the same string value. Actually, the single quoted and double quoted string literals have no difference except if you use the single quoted string and you want to use the single quotation char, you need to use the backslash symbol and vice versa for the double quoted string.  As for the the triple quoted string, it is usually used to represent long string that need the newline on the string like docstrings. Here are the example.

    print '\'hello world!\''
    print "\"hello world!\""
    print """hello
        world
        !"""

String Literals Usage

That was the basic of Python string literals, but I have my own convention on using string literal in order to make the code even tidier. I only use the single quoted string for symbol-like or some kind of identifier like the key on dictionary structure and use the double quoted string for any other general text. Here are the example.
    
    full_names = {
        'edwin': "Edwin Lunando",
        'mirana': "Mirana Nightshade"
    }
As for triple quoted string, I only use it for docstring and very long text like an email template. That's all for today. Thank you. :D