Wednesday 24 April 2013

Python Programming Tutorial 2 - Strings

Python has a built-in string class named 'str'(Java - String) with lot of features. Python strings are immutable which means they can't be changed after creation(Java strings are also immutable). String can be enclosed by either single or double quotes.

Characters in a string can be accessible through [] syntax and python is also zero-based index as Java and C++. Built-in function len(str) returns the length of string(number of characters in input string)

Note: Don't use "len" as a variable name, it will block the len(str) functionality.

[code]>>> s='hi'
>>> s[1]
'i'
>>> len(s)
2[/code]

Below given video, demonstrates the some of the python String literals.

Note: Content was Scrapped from youtube.


In Java the '+' automatically converts the any types to String while appending with String literal but in Python this is not a case. The function str(data) will convert the input data to String.

[code]>>> pi=3.14

>>> str(pi)
'3.14'
>>> 'rrr'+pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'float' objects
>>> 'rrr'+str(pi)
'rrr3.14'
>>> num=18
>>> print "ff" + repr(num)
ff18
>>> print "ff" + `num`
ff18[/code]

Below given video, demonstrates the some of the python String representation.

Note: Content was Scrapped from youtube.



If the value to String literal is prefixed with 'r' and interpreter will pass all the chars without special treatment of backslash '\'.

[code]>>> raw="test\nraw\t.."
>>> print raw
test
raw ..
>>> raw=r"test\nraw\t.."
>>> print raw
test\nraw\t..[/code]

A 'u' prefix allows you to write a unicode string literal (Python has lots of other unicode support features)

[code]>>> data=u'Hello World !'
>>> data
u'Hello World !'
>>> data=u'Hello\u0020World !'
>>> data
u'Hello World !'[/code]

The escape sequence \u0020 indicates to insert the Unicode character with the ordinal value 0x0020 (the space character) at the given position.

1 comment: