Python Strings

In this tutorial you will learn:

  • Strings in Python
  • Immutable and Mutable in Python
  • Joining two Strings
  • String Slicing
  • Finding length of a String

Strings in Python

In the previous tutorial we learned what variables are and how Python deals with variables. In this tutorial we will start by learning the details and usage of String type variable in Python.

    1. myString = “I am a developer”
    2. myHelloString = “Hello”
    3. myWelcomeString = “Welcome”

In Python we can write strings in either three quotes ‘’’Python’’’, two quotes “Developer” or in single quote ‘Code’.

Immutable and Mutable in Python

Understanding the meaning of these two words is very important in order to understand any programming language. In python everything you declare is an object and object are instances which are instances of a larger set called class which has some properties and methods. So Immutable in Python means objects whose value cannot be changed once it is assigned and Mutable means objects whose values can be changed.

Strings are immutable

In Python strings are immutable their value cannot be changed once assigned. It means once you assign a value to a string you cannot assign it another value.
Joining Strings

We can join strings using simple operators

  1. myString1 = “Python”
  2. myString2 = “Programming”
  3. print(myString1 + myString2) #output PythonProgramming

String Slicing

We can access string characters in a number of ways in Python and the most interesting way is through the use of square brackets and then giving a range.

  1. myString1 = “Python”
  2. print(myString1[0]) #should print P
  3. print(myString1[1:4]) #should print yth
  4. print(myString1[-3:-1]) #should print ho

Point to be noted here is that when we start counting P is at 0th position and the last element that falls on 4th position is not included. In case of negative index we consider the last element on 0th position and show the result excluding -3 but including -1.

Finding length of a String

Python contains a very useful method for finding length of a string.

  1. myString1 = “Python”
  2. print(len(myString1)) #gives output of 6
Keep following following for more Python tutorials.

Add new comment