Python String

Intro: string is a data type in Python.

A string is a sequence of characters enclosed in quotes.

We can primarily write a string in three ways:

  1. Single quoted strings : a = ‘Sandeep’
  2. Double quoted strings : b = “Sandeep”
  3. Triple quoted strings : c = ‘’’ Sandeep ‘’’

Python String

A string is usually a bit of text in programming that is written to be displayed to users. It is known to Python when you want to display a string. This is because programmers use either double quote  or single quote  to enclose a word or group of words to express a string.

String Slicing:

A string in Python can be sliced for getting a part of the string.

Consider the following string:

Python String

The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax:

Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the (length-1) index, -2 to (length-2).

Slicing with skip value

We can provide a skip value as a part of our slice like this:

word = “amazing”

word[1:6:2]           # It will return ’mzn’

Other advanced slicing techniques

word = ‘amazing’

word[:7] or word[0:7]      #It will return ‘amazing’

word[0:] or word[0:7]      #It will return ‘amazing’

String Functions

Some of the most used functions to perform operations on or manipulate strings are:

  1. len() function : It returns the length of the string.

len(‘Sandeep’)               #Returns 5

  1. endswith(“rry”) : This function tells whether the variable string ends with the string “rry” or not. If string is “Sandeep”, it returns for “rry” since Sandeep ends with rry.
  2. count(“c”) : It counts the total number of occurrences of any character.
  3. capitalize() : This function capitalizes the first character of a given string.
  4. find(word) : This function finds a word and returns the index of first occurrence of that word in the string.
  5. replace(oldword, newword) : This function replaces the old word with the new word in the entire string.
Escape Sequence Characters:

Sequence of characters after backslash ‘\’ [Escape Sequence Characters]

Escape Sequence Characters comprises of more than one character but represents one character when used within the string.

Examples: \n (new line), \t (tab), \’ (single quote), \\ (backslash), etc.

Exercise:

  1. Write a Python program to display a user-entered name followed by Good Afternoon using input() function.
  2. Write a program to fill in a letter template given below with name and date.
letter = ‘’’ Dear <|NAME|>,

                        You are selected!

                        <|DATE|>
  1. Write a program to detect double spaces in a string.
  2. Replace the double spaces from problem 3 with single spaces.
Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *