String Operations in Python - Letsprogram

Share:
To know basic operations with strings in python : check this post 


String operations in python

Strings can be concatenated (glued together) with the + operator, and repeated with * . You can concatenate strings by operators like + and * 

Strings can be indexed with subscript starts from 0. 
Example : var[0],var[1]
if ,
var = "Python Blog" then var[0] = P , var[10] = g 

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring.

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.Attempting to use an index that is too large will result in an error.

Suppose a Variable var is holding a string in python we can apply operations on var so that it can be concatenated but you cannot the value of var once you had declared to it.This is know as immutable. Strings are immutable in nature so,that we cannot slice a variable like var.

But we all know that python is famous for modules and packages. Everything in python is considered as an object, Python gives you predefined functions for strings to do some operations

NOTE: Object has properties of a class or predefined datatype. That is class has functions in it so that objects can access those functions.

There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments.

Strings may also be created from other objects using the str constructor. Like 
var = str("Python Blog") give you the string.

class str(object=b''encoding='utf-8'errors='strict') returns the String object. str takes an object, encoding, and errors as inputs. encoding and errors are optional,class str(object='')
If they are not given the values then str(object) returns object.__str__() which is informal way to print the string.
 







No comments

F