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.
- myString = “I am a developer”
- myHelloString = “Hello”
- 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
- myString1 = “Python”
- myString2 = “Programming”
- 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.
- myString1 = “Python”
- print(myString1[0]) #should print P
- print(myString1[1:4]) #should print yth
- 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.
- myString1 = “Python”
- print(len(myString1)) #gives output of 6
Add new comment
- 302 views