Python String Tutorial – Python String Functions and Operations
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In this Python String tutorial, you will learn what is Python string with examples.
Moreover, you will learn how to declare and slice a string in python and also look at the Python String functions and Python String operations.
At last, you will learn escape sequences in Python.
So, let’s start the Python String Tutorial.
What is Python String?
A Python string is a sequence of characters. There is a built-in class ‘str’ for handling Python string.
You can prove this with the type() function.
>>> type('Dogs are love')
Output
Python doesn’t have the char data-type like C++ or Java does.
How to Declare Python String?
You can declare a Python string using either single quotes or double quotes.
>>> a='Dogs are love' >>> print(a)
Output
>>> a="Dogs are love" >>> print(a)
Output
However, you cannot use a single quote to begin a string and a double quote to end it, and vice-versa.
>>> a='Dogs are love"
Output
How to Use Quotes inside Python String?
Since we delimit strings using quotes, there are some things you need to take care of when using them inside a string.
>>> a="Dogs are "love""
Output
If you need to use double quotes inside a Python string, delimit the string with single quotes.
>>> a='Dogs are "love"' >>> print(a)
Output
And if you need to use single quotes inside a string, delimit it with double-quotes.
>>> a="Dogs are 'love'" >>> print(a)
Output
You can use as many quotes as you want, then.
>>> a="'Dogs' 'are' 'love'" >> print(a)
Output
Spanning a String Across Lines
When you want to span a Python string across multiple lines, you can use triple quotes.
[php]>>> a="""Hello Welcome""" >>> print(a)[/php]
Output
Welcome
It preserves newlines too, unlike using a backward slash for the same.
>>> a="Hello\ Welcome" >>> print(a)
Output
How to Access the Python String?
A string is immutable; it can’t be changed.
>>> a="Dogs" >>> a[0]="H"
Output
Traceback (most recent call last):File “<pyshell#22>”, line 1, in <module>
a[0]=”H”
TypeError: ‘str’ object does not support item assignment
But you can access a string.
>>> a="Dogs are love" >>> a
Output
>>> print(a)
Output
1. Displaying a single character
To display a single character from a string, put its index in square brackets. Indexing begins at 0.
>>> a[1]
Output
2. Slicing a string
Sometimes, you may want to display only a part of a string. For this, use the slicing operator [].
>>> a[3:8]
Output
Here, it printed characters 3 to 7, with the indexing beginning at 0.
>>> a[:8]
Output
This prints characters from the beginning to character 7.
>>> a[8:]
Output
This prints characters from character 8 to the end of the string.
>>> a[:]
Output
This prints the whole string.
>>> a[:-2]
Output
This prints characters from the beginning to two characters less than the end of the string.
>>> a[-2:]
Output
This prints characters from two characters from the end to the end of the string.
>>> a[-3:-2]
Output
This prints characters from three characters from the string’s end to two characters from it.
The following codes return empty strings.
>>> a[-2:-2]
Output
>>> a[2:2]
Output
Python String Concatenation
Concatenation is the operation of joining stuff together. Python Strings can join using the concatenation operator +.
>>> a='Do you see this, ' >>> b='$$?' >>> a+b
Output
Let’s take another example.
>>> a='10' >>> print(2*a)
Output
Multiplying ‘a’ by 2 returned 1010, and not 20, because ‘10’ is a string, not a number. You cannot concatenate a string to a number.
>>> '10'+10
Output
Traceback (most recent call last):File “<pyshell#49>”, line 1, in <module>
’10’+10
TypeError: must be str, not int
Python String Formatters
Sometimes, you may want to print variables along with a string. You can either use commas, or use string formatters for the same.
>>> city='Ahmedabad' >>> print("Age",21,"City",city)
Output
1. f-strings
The letter ‘f’ precedes the string, and the variables are mentioned in curly braces in their places.
>>> name='Ayushi' >>> print(f"It isn't {name}'s birthday")
Output
Notice that because we wanted to use two single quotes in the string, we delimited the entire string with double quotes instead.
2. format() method
You can use the format() method to do the same. It succeeds the string and has the variables as arguments separated by commas.
In the string, use curly braces to posit the variables. Inside the curly braces, you can either put 0,1,.. or the variables.
When doing the latter, you must assign values to them in the format method.
>>> print("I love {0}".format(a))
Output
>>> print("I love {a}".format(a='cats'))
Output
The variables don’t have to defined before the print statement.
>>> print("I love {b}".format(b='ferrets'))
Output
3. % operator
The % operator goes where the variables go in a string. %s is for string
What follows the string is the operator and variables in parentheses/in a tuple.
>>> b='ferrets' >>> print("I love %s and %s" %(a,b))
Output
Other options include:
%d – for integers
%f – for floating-point numbers
Escape Sequences in Python
In a Python string, you may want to put a tab, a linefeed, or other such things. Escape sequences allow us to do this.
An escape sequence is a backslash followed by a character, depending on what you want to do.
Python supports the following sequences.
- \n – linefeed
- \t – tab
>>> print("hell\to")
Output
- \\ – backslash
Since a backslash may be a part of an escape sequence, so, a backslash must be escaped by a backslash too.
- \’ – A single quote can be escaped by a backslash. This lets you use single quotes freely in a string.
- \” – Like the single quote, the double quote can be escaped too.
Any Doubt yet in Python String and Python String Operations and Functions? Please Comment.
Python String Functions
Python provides us with a number of functions that we can apply on strings or to create strings.
1. len()
The len() function returns the length of a string.
>>> a='book' >>> len(a)
Output
You can also use it to find how long a slice of the string is.
>>> len(a[2:])
Output
2. str()
This function converts any data type into a string.
>>> str(2+3j)
Output
>>> str(['red','green','blue'])
Output
3. lower() and upper()
These methods return the string in lowercase and uppercase, respectively.
>>> a='Book' >>> a.lower()
Output
>>> a.upper()
Output
4. strip()
It removes whitespaces from the beginning and end of the string.
>>> a=' Book ' >>> a.strip()
Output
5. isdigit()
Returns True if all characters in a string are digits.
>>> a='777' >> a.isdigit()
Output
>>> a='77a' >>> a.isdigit()
Output
6. isalpha()
Returns True if all characters in a string are characters from an alphabet.
>>> a='abc' >>> a.isalpha()
Output
>>> a='ab7' >>> a.isalpha()
Output
7. isspace()
Returns True if all characters in a string are spaces.
>>> a=' ' >>> a.isspace()
Output
>>> a=' \' ' >>> a.isspace()
Output
8. startswith()
It takes a string as an argument, and returns True if the string it is applied on begins with the string in the argument.
>>> a.startswith('un')
Output
9. endswith()
It takes a string as an argument, and returns True if the string it is applied on ends with the string in the argument.
>>> a='therefore' >>> a.endswith('fore')
Output
10. find()
It takes an argument and searches for it in the string on which it is applied.
It then returns the index of the substring.
>>> 'homeowner'.find('meow')
Output
If the string doesn’t exist in the main string, then the index it returns is 1.
>>> 'homeowner'.find('wow')
Output
-1
11. replace()
It takes two arguments. The first is the substring to be replaced. The second is the substring to replace with.
>>> 'banana'.replace('na','ha')
Output
12. split()
It takes one argument. The string is then split around every occurrence of the argument in the string.
>>> 'No. Okay. Why?'.split('.')
Output
13. join()
It takes a list as an argument and joins the elements in the list using the string it is applied on.
>>> "*".join(['red','green','blue'])
Output
Python String Operations
1. Comparison Operation in Python
Python Strings can compare using relational operators.
>>> 'hey'<'hi'
Output
‘hey’ is lesser than ‘hi lexicographically (because i comes after e in the dictionary)
>>> a='check' >>> a=='check'
Output
>>> 'yes'!='no'
Output
2. Arithmetic Operation in Python
Some arithmetic operations can be applied on strings.
>>> 'ba'+'na'*2
Output
3. Membership Operation in Python
The membership operators of Python can be used to check if string is a substring to another.
>>> 'na' in 'banana'
Output
>>> 'less' not in 'helpless'
Output
4. Identity Operation in Python
Python’s identity operators ‘is’ and ‘is not’ can be used on strings.
>>> 'Hey' is 'Hi'
Output
>>> 'Yo' is not 'yo'
Output
5. Logical Operation in Python
Python’s and, or, and not operators can be applied too. An empty string has a Boolean value of False.
a. and- If the value on the left is True it returns the value on the right.
Otherwise, the value on the left is False, it returns False.
>>> '' and '1'
Output
>>> '1' and ''
Output
b. or- If the value on the left is True, it returns True. Otherwise, the value on the right is returned.
c. not- As we said earlier, an empty string has a Boolean value of False.
>>> not('1')
Output
>>> not('')
Output
This was all about the tutorial on Python strings. Hope you like the Python strings tutorial.
Conclusion
In this Python String tutorial, you learned about python string with string functions and Operators, and how to declare and access them.
Then you learned about python string concatenation and formatters in python.
Finally, You learned about Python string functions and operations that you can perform on strings.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google
In strings , you can’t print s[-1:-4]. it doesn’t support negative or reverse slicing
step direction required where its -ve index or +ve index
case 1: its -ve index u can get result from -ve index – to -3
case2: its +ve index u can get empty string result.
Hello Rakshith,
Thanks for connecting DataFlair.
Let the string be s=’helloworld’
s[-1:-4] gives us an empty string because it cannot traverse from index -1 to -4 LEFT TO RIGHT.
But it can traverse that right to left; for that, we give it a step value of -1.
So, s[-1:-4:-1] gives us ‘dlr’.
And if you want this value traversed left to right, you can try s[-3:] instead. It will give you ‘rld’.
Hope, it helps you!
Please Give explanation and example of Extended Slices ex : [1:10:2], L[:-1:1], L[::-1]
Hello Narendra,
L[:4] looks like a regular slice. An extended slice also takes a value for step/stride.
Take an example.
This is list L=[1,2,3,4,5,6,7,8,9,10].
L[1:10:2] is the slice with these values: [2, 4, 6, 8, 10].
It starts with the first index and takes a step of 2. So, it takes values from the indices 1, 3, 5, 7, and 9.
L[:-1:1] traverses from the beginning to one from the end, giving us values 1 to 9.
L[::-1] traverses the entire list from right to left because it has a step value of -1.
Hope, it helps. Keep Visiting DataFlair
Hello Narendra Pratap Singh,
[1:10:2] works like that [first number, last number, rise(difference]
for example a=”abcdefghij”
[1:10:2] prints –> ‘bdfhj’
[::-1] prints–> from last to first element “jih….a”
[:-1:1] this one is hard to understand lol
id like an explanation for this too!
The instruction a[:-1:1] prints ‘abcdefghi’. This is because, here the starting index is not mentioned so 0 and ending instruction is -1, which means the last index and increment is 1. So, starting from the first character, every character (since increment is 1) is given as output till the last character (the last one excluded). Hoping that you understood the given explanation.
Hello, there is a problem on this site. For example, if I have a question I ask this on here, and even if its answered by you, I dont have any notification on my mail adress.
So i have to come here to see if its answered.
But i’d like to get notification when its answered.
How to solve this problem?
Thank you
#Data Flair for making the amazing site that very helpful for Developer .
Thanks manoj for your appreciation. Hope DataFlair tutorials will help you in becoming Good developer.