This page looks best with JavaScript enabled

Python - Strings

 ·   ·  β˜• 4 min read

Python - String

In Python, string is an immutable sequence data type. It is the sequence of Unicode characters wrapped inside single, double, or triple quotes.

The followings are valid string literals in Python.

'This is a string in Python' # string in single quotes
"This is a string in Python" # string in double quotes
'''This is a string in Python''' # string in triple quotes
"""This is a string in Python""" # string in triple double-quotes

A string literal can be assigned to a variable, as shown below.

str1='This is a string in Python' 
print(str1)
str2="This is a string in Python" 
print(str2)

Output:

This is a string in Python
This is a string in Python

Multi-line strings must be embed in triple quotes, as shown below.

str1='''This is 
the first
Multi-line string.
'''
print(str1)

str2="""This is
the second
Multi-line
string."""
print(str2)

Output:

This is 
the first
Multi-line string.

This is
the second
Multi-line
string.

If a string literal required to embed double quotes as part of a string then, it should be put in single quotes. Likewise, if a string includes a single quote as a part of a string then, it should be written in double quotes.

str1='Welcome to "Python Tutorial" on TutorialsTeacher'
print(str1)

str2="Welcome to 'Python Tutorial' on TutorialsTeacher"
print(str2)

Output:

Welcome to "Python Tutorial" from TutorialsTeacher
Welcome to 'Python Tutorial' on TutorialsTeacher

Use the len() function to retrieve the length of a string, as shown below.

>>> greet='Hello'
>>> len(greet)
5

A sequence is defined as an ordered collection of items. Hence, a string is an ordered collection of characters. The sequence uses an index, starting with zero to fetch a certain item (a character in case of a string) from it.

>>> greet='hello'
>>> greet[0]
'h'
>>> greet[1]
'e'
>>> greet[2]
'l'
>>> greet[3]
'l'
>>> greet[4]
'o'
>>> greet[5] # throw error if index > len(string)-1
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[5]
IndexError: string index out of range

Python supports negative indexing too, starting with -(length of string) till -1.

>>> greet='hello'
>>> greet[-5]
'h'
>>> greet[-4]
'e'
>>> greet[-3]
'l'
>>> greet[-2]
'l'
>>> greet[-1]
'o'

The string is an immutable object. Hence, it is not possible to modify it. The attempt to assign different characters at a certain index results in errors.

>>> greet='hello'
>>> greet[0]='A'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
greet[0]='A'
TypeError: 'str' object does not support item assignment

str Class

All strings are objects of the str class in Python.

>>> greet='hello'
>>> type(greet)
<class 'str'>

Use the str() function to convert a number to a string.

>>> str(100)
'100'
>>> str(-10)
'-10'
>>> str(True)
'True'

Escape Sequences

The escape character is used to invoke an alternative implementation of the subsequent character in a sequence. In Python, backslash \ is used as an escape character. Use a backslash character followed by the character you want to insert in a string e.g. ' to include a quote, or " to include a double quotes in a string, as shown below.

str1='Welcome to \'Python Tutorial\' on TutorialsTeacher'
print(str1)

str2="Welcome to \"Python Tutorial\" on TutorialsTeacher"
print(str2)

Output:

Welcome to 'Python Tutorial' from TutorialsTeacher
Welcome to "Python Tutorial" on TutorialsTeacher

Use r or R to ignore escape sequences in a string.

str1=r'Welcome to \'Python Tutorial\' on TutorialsTeacher'
print(str1)

Output:

Welcome to \'Python Tutorial\' from TutorialsTeacher

Escape sequences in Python.

\\ 	Backslash 	>>> "Hello\\Hi"
Hello\Hi
\b 	Backspace 	>>> "ab\bc"
ac
\f 	Form feed 	
\n 	Newline 	>>> "hello\nworld"
Hello
world
\nnn 	Octal notation, where n is in the range 0-7 	>>> '\101'
A
\t 	Tab 	>>> 'Hello\tPython'
Hello    Python
\xnn 	Hexadecimal notation, where n is in the range 0-9, a-f, or A-F 	>>> '\x48\x69'
Hi
\onn 	Octal notation, where n is in the range 0-9 	>>> "\110\151"
Hi 

Python Operations

#+ 	Appends the second string to the first 	>>> a='hello'
>>> b='world'
>>> a+b
#'helloworld'
#* 	Concatenates multiple copies of the same string 	>>> a='hello'
>>> a*3
#'hellohellohello'
#[] 	Returns the character at the given index 	>>> a = 'Python'
>>> a[2]
t
#[ : ] 	Fetches the characters in the range specified by two index operands separated by the : symbol 	>>> a = 'Python'
>>> a[0:2]
#'Py'
#in 	Returns true if a character exists in the given string 	>>> a = 'Python'
>>> 'x' in a
#False
>>> 'y' in a
#True
>>> 'p' in a
#False
#not in 	Returns true if a character does not exist in the given string 	>>> a = 'Python'
>>> 'x' not in a
#True
>>> 'y' not in a
#False

Ohidur Rahman Bappy
WRITTEN BY
Ohidur Rahman Bappy
πŸ“šLearner 🐍 Developer