A string is a sequence of characters. A python string maybe enclosed within single quotes ' '
, double quotes " "
or triple quotes ''' '''
.
Strings enclosed within triple quotes is called as documentation string and may extend over several lines!
Python strings are immutable
which means a component of a string cannot be altered and any attempt to do so would lead to error.
Basic string operations
Concatenation of strings : The
+
is known as a concatenation operator which is used to integrate multiple strings into a single string. Tip - You can add space between the strings by adding space before and after the quotes!Repetition of string : The
*
is used to repeat a string for a specifies number of times. Tip - You can add space between the strings by adding space before and after the quotes!Max() function: To find the largest value of all strings.
Min() function: To find the smallest value of all strings.
Indexing
Individual characters within a string are accessed using a technique called indexing.
The indices for any string start from 0 and end with one less than the length of the string i.e. N-1
.
Python allows both negative and non-negative indexing where negative indexing is used to access the string from the right end.
EXAMPLE
Slicing
String slicing is done to retrieve a substring or a slice from a complete string which can be done by specifying an index range.
- To retrieve a substring having indices from start to end - 1, we specify the range as
start : end
. - To retrieve a substring using the default start index ( 0 ), we specify the range as
: end
. - To retrieve a substring using the default end index [len(msg)-1], we specify the range as
start :
. - To retrieve a substring using the arbitrary slicing values, we specify the range as
value1 : value2
. - To retrieve a consecutive subsequence of characters , we use
start : end : inc
; which will also include the element at the positioninc
in the range.
Membership
Python also allows us to check for membership or the presence of individual characters or substrings in strings using in
operator. The answer is evaluated as a boolean value.
Follow up to have the complete beginner friendly python notes with you!