The most commonly used Object in any project and in any programming language is String Only.
Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a string.
How to define multi – line String literals :
We define multi-line string literals by using triple single or double quotes.
How to access characters of a String:
We can access characters of a string by using the following ways.
- By using index
- By using slice Operator
By Using Index:
Python supports both + ve and – ve index.
+ ve index means from left to right (forward direction )
– ve index means from Right to Left ( Backward direction)
Accessing characters by using slice operator:
Beginindex: from where we have to consider slice.
Endindex: we have to terminate slice at endindex-1
Step: incremented value
Note: if we are not specifying beginindex then it will consider from beginning of the string.
If we are not specifying end index then it willconsider up to end of the string.
The default value for step is 1.
S=”learning python is very very easy!!!”
‘g python is very very easy!!!’
Mathematical Operators for String:
We can apply the following mathematical operators for strings.
- + Operator for concatenation.
- * operator for repetition.
- To use + operator for strings, compulsory both arguments should be str type
- To use * operator for strings, compulsory one arguments should be str and other argument should be int.
len() in-built function:
we can use len() function to find the number of characters present in the string.
We can check whether the character or string is the member of another string or not by using in and not in operators.
Print(‘t’ in s) #true
Print(‘a’ in s) #False
Comparison of Strings:
We can use comparison operators (<,<=,>,>= ) and equality operators ( ==,!= )for strings.
Comparison will be performed based on alphabetical order.
Removing spaces from the string:
We can use the following 3 methods
- rstrip() : To remove spaces at right hand side
- lstrip() : To remove spaces at Left hand side
- strip() : To removes spaces both sides.
Replacing a string with another string:
s.replace (oldstring, newstring)
inside s, every occurrence of oldstring will be replaced with newstring
Splitting of Strings:
We can split the given string according to specified separator by using split() method.
the default separator is space. The return type of split() method is List.
Joining of Strings :
We can join a group of strings( list or tuple )wrt the given separator.
S=separator.join(group of strings)
t=(‘sunny’, ‘bunny’, ‘chinny’)