Strings in Python are ordered collection of characters used to represent text based information. In Python v3 we can identify 3 types of string data types objects- unicode, bytes and bytearray. ASCII characters is an example of unicode and so are other languages. Byte string data types are used for binary encoded data. Bytearray is mutable version of byte string type.

Here we deal with ASCII unicode based strings which are used for English based text processing, naming etc. Strings in Python are immutable sequence with left to right positional order and once declared cannot be changed(immutable). Strings literals are written within single or double quotation marks. Empty string will have nothing between the quotation mark. Once string is declared we can do different operation such as slicing, calculating the number of characters in the string, concatenating strings, replacing part of strings, repeating strings and so on. These operation are performed using methods specific to strings.

Some basic string declaration in Python are shown below:


Empty string:

>>> s = ''
>>> s
''

String with single quote ' in a sentence.

If you place a single quote within the double it's fine:

>>> s = "It's Thursday"
>>> s
"It's Thursday"

If you want to place the string within single quote still need to preserve single quote that happens to be used in sentences then use the backslash.

>>> s = 'It\'s Thrusday'
>>> s
"It's Thrusday"

Dealing with escape sequences

 One example use of escape sequence using backslash was shown earlier for placing a single quote in a string. There are other places where escape sequence are required, for example in embedding any character codes such as double quotes, for embedding newline, backspaces, embedding binary, octal or hexadecimal numbers and so on.

Here is example of embedding double quote in strings if required:

>>> s = "He said- \"I am tall\""
>>> s
'He said- "I am tall"'

To insert tab, new lines etc for printing purposes:

>>> s = "S.No\tNames\n1\tJonny"
>>> print(s)
S.No    Names
1          Jonny


In python language, if python does not detect valid escape character then it automatically inserts another backslash as the following examples shows:

>>> mypath = "d:\python\codes"
>>> mypath
'd:\\python\\codes'


Triple quotes:

Triple quotes are used create a block of strings. Usually they are used for example in writing some help messages which are often long or printing out long messages.

 Printing out messages:

>>> print("""\
Student Record
     Name:  Jonny
     Age: 24
""")
Student Record
     Name:  Jonny
     Age: 24

Although, not meant for the triple quote are often used to comment out parts of codes for debugging purposes and others.

So we have here explained the basic of writing strings in Python programming language. In the next python tutorial we explain Processing strings in Python Programming Language.

0 comments:

Post a Comment

 
Top