Auto AdSense

Saturday, 24 January 2015

Python Strings



  • Accessing Values in Strings:
    #!/usr/bin/python

    var1 = 'Hello World!'
    var2 = "Python Programming"

    print "var1[0]: ", var1[0]
    print "var2[1:5]: ", var2[1:5]
  • Output
    var1[0]: H
    var2[1:5]: ytho
  • Updating Strings:
    #!/usr/bin/python

    var1 = 'Hello World!'

    print "Updated String :- ", var1[:6] + 'Python'
  • Output
    Updated String :- Hello Python
  • String Formatting Operator:
    #!/usr/bin/python

    print "My name is %s and weight is %d kg!" % ('Zara', 21)
  • Output
    My name is Zara and weight is 21 kg!
  • Triple Quotes:
    #!/usr/bin/python

    para_str = """this is a long string that is made up of
    several lines and non-printable characters such as
    TAB ( \t ) and they will show up that way when displayed.
    NEWLINEs within the string, whether explicitly given like
    this within the brackets [ \n ], or just a NEWLINE within
    the variable assignment will also show up.
    """
    print para_str;
  • Output
    this is a long string that is made up of
    several lines and non-printable characters such as
    TAB ( ) and they will show up that way when displayed.
    NEWLINEs within the string, whether explicitly given like
    this within the brackets [
    ], or just a NEWLINE within
    the variable assignment will also show up.
  • Raw String:
    #!/usr/bin/python

    print 'C:\\nowhere'
  • Output
    C:\nowhere
  • Unicode String:
    #!/usr/bin/python

    print u'Hello, world!'
  • Output
    Hello, world!      

No comments:

Post a Comment