Best post on string datatype in python – 1

String Datatype in Python

Python supports many simple and compound datatypes.

Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.

Mutable datatypes means changes can be done and are reflected in same variable.

Immutable datatypes means changes can be done but not in same variable.

String is collection or sequence of characters.

An empty string represents zero character or we can call it as null string.

A string datatype can be defined with use of single or double quotes.

Accessing a string

A string can be accessed using square brackets [].

Example

>>> itv="itvoyagers"
>>> itv[0]
'i'
>>> itv[6]
'g'
>>> itv[10]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in
itv[10]
IndexError: string index out of range
>>>

 

Above example consist of a string having 10 characters and index position starting from 0 till 9. To access a string we need to pass index value inside square brackets to retrieve character located on that index. As last index number is 9 we get and IndexError if we pass an index greater than 9. So first letter ‘i’ is at position 0, second letter ‘t’ is at position 1 and so on..

Example:

>>> itv="itvoyagers"
>>> itv[2.5]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in
itv[2.5]
TypeError: string indices must be integers
>>>

From above example it is clear that we cannot use a float value as index. An index should always be an integer and last value of index will always be n-1 if total length is n.

len function or len()

Python provides a built-in function called as len() to calculate number of characters in a string or simply we can say length of a string.

We cannot calculate length of integers using len(). To calculate length of integers we must type cast it in string and then apply len() .

Example:

>>> itv="itvoyagers"
>>> len(itv)
10
>>> itv2="itvoyagers is an educational blog"
>>> len(itv2)
33
>>> itv3=""
>>> len(itv3)
0
>>> itv4=" "
>>> len(itv4)
1
>>>

If we wish to get last letter of the string we might script it as follows:

>>> itv="itvoyagers"
>>> h=len(itv)
>>> last=itv[h]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
last=itv[h]
IndexError: string index out of range
>>> 

This raises an IndexError. So to over come this we can modify code using following script:

>>> itv="itvoyagers"
>>> h=len(itv)
>>> last=itv[h-1]
>>> last
's'
>>>

Negative Indexing

We can use negative indexing for string datatype which will help us to count backward from the end of the string.

If we use itv[-1] it will give output as ‘s’.

>>> itv="itvoyagers"
>>> itv[-1]
's'
>>> itv[-2]
'r'
>>> itv[-9]
't'
>>> itv[-10]
'i'
>>> itv[-11]
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
itv[-11]
IndexError: string index out of range
>>>

In negative indices, index begins with -1 and not 0 so last value of indexing will be -10 in our example and not -9.

Traversing string using for loop

Traversing is a process of moving in an iterable and locating values from index position.

In this case our iterable is of type string and loop used is for loop.

>>> itv="itvoyagers"
>>> for i in itv:
print("Letter is",i)

Output:

Letter is i
Letter is t
Letter is v
Letter is o
Letter is y
Letter is a
Letter is g
Letter is e
Letter is r
Letter is s

String slicing

A string datatype can be sliced using [ : ] .

Syntax:

[start : end : step]

This provide start and end value.

Sometimes a step value is also mentioned after end value using colon separation.

In below example we will see multiple outputs or multiple ways to slice a string datatype.

 

Example:

#string slicing
demo_string = "Itvoyagers is a blog"
print('demo_string[0:5]',demo_string[0:5])
print('demo_string[9:12]',demo_string[9:12])
print('demo_string[5:12]',demo_string[5:12])
print('demo_string[:3]',demo_string[:3])
print('demo_string[3:]',demo_string[3:])
print('demo_string[3:3]',demo_string[3:3])
print('demo_string[:]',demo_string[:])
print('demo_string[0]',demo_string[0])
print('demo_string[10]',demo_string[10])
print('demo_string[5]',demo_string[5])
print('demo_string[5:14:2]',demo_string[5:14:2])
print('demo_string[5::2]',demo_string[5::2])
print('demo_string[:14:2]',demo_string[:14:2])
print('demo_string[5:1:-2]',demo_string[5:1:-2])
print('demo_string[5:1:-1]',demo_string[5:1:-1])
print('demo_string[::]',demo_string[::])

Output:

slicing of string datatype
slicing of string datatype

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
Best post on Select Query to Search & Read: Python + MySQL-4
Best post on Update query and Delete query : Python + MySQL-4
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment