Best post immutable string,string operations python-2

String datatype and string operations

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.

No separate character type is required instead we can have string of length 1.

String datatype is Immutable

As we know immutable data type indicates datatypes which are non editable or unchangeable in same variable name.

We cannot modify existing string and so strings are immutable datatype.

We can create a new string with reference to existing or orignal string .

Strings are immutable - Justified

If we try to change or assign any new value using [ ] operator in existing string, we get an error message.

Example:

>>> itv='Welcome to itvoyagers'
>>> itv[11]='I'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
itv[11]='I'
TypeError: 'str' object does not support item assignment
>>>

This TypeError: ‘str’ object does not support item assignment proves that we cannot modify our existing string.

In our case itv holds original string and itv[11]=’I’ tries to edit original string at position 11 with

As we receive above message, it becomes that string datatype cannot update original value and strings are immutable.

How to deal with immutable string?

To remove TypeError while updating string, we can create a new string based on existing string.

Example:

>>> itv='Welcome to itvoyagers'
>>> new_itv=itv[:11] + 'I' + itv[12:]
>>> new_itv
'Welcome to Itvoyagers'
>>> new_itv1='Hello'+' ' + itv[11:]
>>> new_itv1
'Hello itvoyagers'

 This example tells us about how to update a string with new variable.

In this example concatenation of string slicing is done with string.

According to the location of character which we wish to update we can slice the string and concatenate with required update 

How to search in a string?

We can search a string or letter from a string.

Following example will help us for better understanding :

Example:

def search_a_string(word,letter):
for i in range(len(word)):
if word[i]==letter:
print("match found")
break
else:
print("match not found")

Output:

>>> search_a_string("itvoyagers","L")
match not found
>>> search_a_string("itvoyagers","v")
match found
>>>

This example indicates that while searching a letter or character case sensitivity must be considered.

Looping and counting on string

We can use loops for counting or traversing a string.

Following example will help us for better understanding :

Example:

#Script to calculate number of times i exists in itvoyagers.in
itv='itvoyagers.in'
counter = 0
for letter in itv:
if letter =='i':
counter+=1
print("Count of i in itvoyagers.in is ", counter)

Output:

>>> 
Count of i in itvoyagers.in is 2

This example indicates that by using loops and counter we can easily find count of letters present in particular string.

String Operations

Python supports various string operations which helps in performing tasks easily.

Various string operations include concatenation, repetition, in operator, not in operator, range and slice operators.

Some of the string operations are explained below:

 

List of string operations in python​

  • + : Concatenation operator
    • This operator is used to join or merge two strings together, i.e. values to the either side of + operator will be merged or concatenated.
    • >>> s="python"
      >>> s1="programming"
      >>> s+s1
      'pythonprogramming'
      >>> s+" "+s1
      'python programming'
  • * : Repetition operator
    • This operator creates new string by creating copies of same string. 
    • This operator here does not multiply number with string but it creates copies of string as per specified number.
    • >>> s="python "
      >>> s*3
      'python python python '
  • [] : Slice operator
    • This operator is used to get a character from the given string by specifying the index position in [].
    • >>> s='python programming'
      >>> s[6]
      ' '
      >>> s[12]
      'a'
      >>> s[13]
      'm'
  • [:]  : Range Slice operator
    • This operator is used to slice a string by specifying start and end position and also an optional parameter of step value.
    • >>> s='python programming'
      >>> s[6:14]
      ' program'
      >>> s[4:14]
      'on program'
      >>> s[4:14:2]
      'o rga'
      >>> s[14:4:-2]
      'magr '
  • in : Membership operator (in)
    • This operator will return True is character is present in given string and False otherwise.
    • >>> s='python programming'
      >>> 'n' in s
      True
      >>> 'N' in s
      False
  • not in : Membership operator(not in)
    • This operator will return True is character is not present in given string and False otherwise.
    • >>> s='python programming'
      >>> 'n' not in s
      False
      >>> 'N' not in s
      True

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
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