Strings in python

Strings in python

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! Capture.PNG

Python strings are immutable which means a component of a string cannot be altered and any attempt to do so would lead to error. image.png

Basic string operations

  • Concatenation of strings : The + is known as a concatenation operator which is used to integrate multiple strings into a single string. image.png 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. image.png 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. image.png

  • Min() function: To find the smallest value of all strings. image.png

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

image.png image.png

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. image.png
  • To retrieve a substring using the default start index ( 0 ), we specify the range as : end. image.png
  • To retrieve a substring using the default end index [len(msg)-1], we specify the range as start :. image.png
  • To retrieve a substring using the arbitrary slicing values, we specify the range as value1 : value2. image.png
  • To retrieve a consecutive subsequence of characters , we use start : end : inc; which will also include the element at the position inc in the range. image.png

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. image.png

Follow up to have the complete beginner friendly python notes with you!