Python String Tutorial – Python String Functions & Operations

Free Python course with 25 projects (coupon code: DATAFLAIR_PYTHON) Start Now

1. Python String Tutorial

In this Python String tutorial, we will discuss what is Python string and its examples. Moreover, we 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, we cover escape sequences in Python. As we saw earlier, you don’t need to mention the data type when declaring a string.

So, let’s start the Python String Tutorial.

Python Strings

Python Strings Tutorial – Functions and Operations

Learn: Bitwise Operator in Python with Syntax and Example

2. 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')

<class ‘str’>

Python doesn’t have the char data-type like C++ or Java does.

Learn: Comparison Operator in Python with Syntax and Examples

3. How to Declare Python String?

You can declare a Python string using either single quotes or double quotes.

>>> a='Dogs are love'
>>> print(a)

Dogs are love

>>> a="Dogs are love"
>>> print(a)

Dogs are love

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"

SyntaxError: EOL while scanning string literal

Python Operators with Syntax and Examples

4. 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""

SyntaxError: invalid syntax

If you need to use double quotes inside a Python string, delimit the string with single quotes.

>>> a='Dogs are "love"'
>>> print(a)

Dogs are “love”

And if you need to use single quotes inside a string, delimit it with double quotes.

>>> a="Dogs are 'love'"
>>> print(a)

Dogs are ‘love’

You can use as many quotes as you want, then.

>>> a="'Dogs' 'are' 'love'"
>> print(a)

‘Dogs’ ‘are’ ‘love’

Also refer to section 9 for how to escape quotes.

Learn: Python Namespace and Variable Scope – Local and Global Variables

5. Spanning a String Across Lines

When you want to span a Python string across multiple lines, you can use triple quotes.

[php]>>> a="""Hello
>>> print(a)[/php]

It preserves newlines too, unlike using a backward slash for the same.

>>> a="Hello\
>>> print(a)

Hello      Welcome

Learn: Python Decision Making Statements with Syntax and Examples

6. How to Access Python String?

A string is immutable; it can’t be changed.

>>> a="Dogs"
>>> a[0]="H"

Traceback (most recent call last):

File “<pyshell#22>”, line 1, in <module>


TypeError: ‘str’ object does not support item assignment

But you can access a string.

>>> a="Dogs are love"
>>> a

‘Dogs are love’

>>> print(a)

Dogs are love

i. Displaying a single character

To display a single character from a string, put its index in square brackets. Indexing begins at 0.

>>> a[1]


b. Slicing a string

Sometimes, you may want to display only a part of a string. For this, use the slicing operator [].

>>> a[3:8]

‘s are’

Here, it printed characters 3 to 7, with the indexing beginning at 0.

>>> a[:8]

‘Dogs are’

This prints characters from the beginning to character 7.

>>> a[8:]

‘ love’

This prints characters from character 8 to the end of the string.

>>> a[:]

‘Dogs are love’

This prints the whole string.

>>> a[:-2]

‘Dogs are lo’

This prints characters from the beginning to two characters less than the end of the string.

>>> a[-2:]


This prints characters from two characters from the end to the end of the string.

>>> a[-3:-2]


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]

>>> a[2:2]

Learn: Loops in Python with Syntax and Examples

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

‘Do you see this, $$?’

Let’s take another example.

>>> a='10'
>>> print(2*a)


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

Traceback (most recent call last):

File “<pyshell#49>”, line 1, in <module>


TypeError: must be str, not int

Learn: Loops in Python with Syntax and Examples

8. 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)

Age 21 City Ahmedabad

i. 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")

It isn’t Ayushi’s birthday

Notice that because we wanted to use two single quotes in the string, we delimited the entire string with double quotes instead.

ii. 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))

I love dogs

>>> print("I love {a}".format(a='cats'))

I love cats

The variables don’t have to defined before the print statement.

>>> print("I love {b}".format(b='ferrets'))

I love ferrets

c. % 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))

I love dogs and cats

Other options include:

%d – for integers

%f – for floating-point numbers

Learn: Python Functions with Syntax and Examples

9. 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")

hell         o

  • \\ – 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.

Learn: Python Function Arguments with Types, Syntax and Examples

10. Python String Functions

Python provides us with a number of functions that we can apply on strings or to create strings.

a. len()

The len() function returns the length of a string.

>>> a='book'
>>> len(a)


You can also use it to find how long a slice of the string is.

>>> len(a[2:])


b. str()

This function converts any data type into a string.

>>> str(2+3j)


>>> str(['red','green','blue'])

“[‘red’, ‘green’, ‘blue’]”

c. lower() and upper()

These methods return the string in lowercase and uppercase, respectively.

>>> a='Book'
>>> a.lower()


>>> a.upper()


d. strip()

It removes whitespaces from the beginning and end of the string.

>>> a='  Book '
>>> a.strip()


e. isdigit()

Returns True if all characters in a string are digits.

>>> a='777'
>> a.isdigit()


>>> a='77a'
>>> a.isdigit()


f. isalpha()

Returns True if all characters in a string are characters from an alphabet.

>>> a='abc'
>>> a.isalpha()


>>> a='ab7'
>>> a.isalpha()


g. isspace()

Returns True if all characters in a string are spaces.

>>> a='   '
>>> a.isspace()


>>> a=' \'  '
>>> a.isspace()


h. startswith()

It takes a string as an argument, and returns True is the string it is applied on begins with the string in the argument.

>>> a.startswith('un')


i. 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')


j. 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')


If the string doesn’t exist in the main string, then the index it returns is 1.

>>> 'homeowner'.find('wow')

k. 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')


l. split()

It takes one argument. The string is then split around every occurrence of the argument in the string.

>>> 'No. Okay. Why?'.split('.')

[‘No’, ‘ Okay’, ‘ Why?’]

m. 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'])


Learn: Python Functions with Syntax and Examples

11. Python String Operations

Python String Operations

Python String Operations

a. Comparison

Python Strings can compare using the relational operators.

>>> 'hey'<'hi'


‘hey’ is lesser than ‘hi lexicographically (because i comes after e in the dictionary)

>>> a='check'
>>> a=='check'


>>> 'yes'!='no'


b. Arithmetic

Some arithmetic operations can be applied on strings.

>>> 'ba'+'na'*2


c. Membership

The membership operators of Python can be used to check if string is a substring to another.

>>> 'na' in 'banana'


>>> 'less' not in 'helpless'


d. Identity

Python’s identity operators ‘is’ and ‘is not’ can be used on strings.

>>> 'Hey' is 'Hi'


>>> 'Yo' is not 'yo'


e. Logical

Python’s and, or, and not operators can be applied too. An empty string has a Boolean value of False.

1. 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'

>>> '1' and ''

2. or- If the value on the left is True, it returns True. Otherwise, the value on the right is returned.

3. not- As we said earlier, an empty string has a Boolean value of False.

>>> not('1')


>>> not('')


This was all about the tutorial on Python strings. Hope you like the Python strings tutorial.

12. Python String – Conclusion

In this Python String tutorial, we learned about python string with string functions and Operators , and how to declare and access them. Then we learned about python string concatenation and formatters in python. We also learned about Python string functions. Lastly, we looked at operations that we can perform on strings. Hope you enjoyed today’s lesson. Leave your feedback in the comments if any query on Python strings.

Check Must Read Python Books for Programming in Python

8 Responses

  1. rakshith says:

    In strings , you can’t print s[-1:-4]. it doesn’t support negative or reverse slicing

    • krishna says:

      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.

    • DataFlair Team says:

      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!

  2. Narendra Pratap Singh says:

    Please Give explanation and example of Extended Slices ex : [1:10:2], L[:-1:1], L[::-1]

    • DataFlair Team says:

      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

  3. Semih says:

    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!

  4. Semih says:

    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

  5. Manoj Kumar says:

    #Data Flair for making the amazing site that very helpful for Developer .

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.