Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


Python Strings

Strings are one of the most common data types in Python. It is used for storing text. It can be created by enclosing characters either in single quotation marks or double quotation marks. It can be assigned to a variable using = sign.

MyString = "Hello World!"
MyString = 'Hello World!'

Python Multi-line Strings

Multi-line string can be created by enclosing the block either in three single quotation marks or three double quotation marks.

MyString = """Python 
programming"""

MyString = '''Python 
programming'''

Access character of a String

A character (also called element) of a string can be accessed with it's index number. In Python, index number starts with 0 in forward direction and -1 in backward direction. The below figure and example describe the indexing concept of a string.

String Indexing:

Python String Indexing

The below example describes how to access character of a string using its index number.

MyString = 'Python'

#forward indexing
print(MyString[0]) 

#backward indexing 
print(MyString[-1])  

The output of the above code will be:

P 
n   

Access range of characters of a String

Range of characters of a string can be selected using statement like [start_index : end_index] where end_index is excluded. If start_index and end_index are not mentioned then it takes first and last index numbers of the string respectively.

MyString = 'Learn Python'
print(MyString[0:5])
print(MyString[-12:-7])

print(MyString[6:])
print(MyString[:-7])

print(MyString[:])

The output of the above code will be:

Learn
Learn

Python
Learn

Learn Python   

String Length

The len() function can be used to find out total number of characters in the string.

MyString = 'Learn Python'
print(len(MyString))

The output of the above code will be:

12

Check a character(s) in the String

If control statement is used to check whether the string contains specified character(s) or not.

MyString = 'I am learning Python programming.'
if 'programming' in MyString:
  print('Yes, It is present in the string.')
else:
  print('No, It is not present in the string.')

The above code will give the following output:

Yes, It is present in the string.

String Concatenation

Two strings can be joined using + operator.

text_1 = 'Learn'
text_2 = 'Python'
MyString = text_1 + text_2
print(MyString)

MyString = text_1 + " " + text_2
print(MyString)

The above code will give the following output:

LearnPython

Learn Python

String format() Method

Strings can not be added with numbers by using + operator. For combining string with a number, format method is used. A user can pass parameter(s) in format() method, which is further placed into its respective placeholder {}. This method can take unlimited number of parameters. Along with this, an index number (starts with 0) can also be used with placeholders. Please see example below:

in_time = 9
out_time = 18
MyString = "I will reach office at {} hrs and leave office at {} hrs."
print(MyString.format(in_time, out_time))

in_time = 9
out_time = 18
MyString = "I will reach office at {1} hrs and leave office at {0} hrs."
print(MyString.format(out_time, in_time))

The above code will give the following output:

I will reach office at 9 hrs and leave office at 18 hrs.

I will reach office at 9 hrs and leave office at 18 hrs.

String Methods

Python has number of string methods. Here, few very common string functions are discussed.

  • lower(): Returns string in lowercase
  • upper(): Returns string in uppercase
  • strip(): Removes whitespaces from start and end of the string
  • replace(): replace specified character(s) with another specified character(s)
  • split(): Split the string by specified separator and returns substrings in a list.
  • count(): Returns number of occurrence of specified character(s) in the string

Example: lower(), upper() and strip() String Methods

The below example shows how to use lower(), upper() and strip() methods in python.

MyString = "Learn Python"
print(MyString.lower())
print(MyString.upper())

MyString = "  Learn Python  "
print(MyString.strip())

The above code will give the following output:

learn python

LEARN PYTHON

Learn Python

Example: replace(), split() and count() String Methods

In the below example replace(), split() and count() methods is used while working with a string.

MyString = "Learn Python"
print(MyString.replace("Python", "C++"))

MyString = "Learning Python is fun"
print(MyString.split(" "))

MyString = "This is Python programming."
print(MyString.count('is'))

The above code will give the following output:

Learn C++

['Learning', 'Python', 'is', 'fun']

2




String Methods & Functions
MethodsDescription
capitalize() Converts first character of first world into uppercase and rest into lowercase.
casefold() Converts string into lower case.
center() Returns a centered string.
count() Returns the number of times a specified value occurs in a string.
encode() Returns an encoded version of the string.
endswith() Returns true if the string ends with the specified value.
expandtabs() Sets the tab size of the string.
find() Searches the string for a specified value and returns the position of where it was found.
format() Formats specified values in a string.
format_map() Formats specified values in a string.
index() Returns the index number for first occurrence of specified character sequence in the string.
isalnum() Returns true when all characters of the string are alphanumeric, else returns false.
isalpha() Returns true when all characters of the string are alphabet, else returns false.
isdecimal() Returns true when all characters of the string are decimals, else returns false.
isdigit() Returns true when all characters of the string are digits, else returns false.
isidentifier() Returns true when the string is an identifier, else returns false.
islower() Returns true when all characters of the string are in lowercase, else returns false.
isnumeric() Returns true when all characters of the string are numeric, else returns false.
isprintable() Returns true when all characters of the string are printable, else returns false.
isspace() Returns true when all characters of the string are whitespaces, else returns false.
istitle() Returns true when the characters of the string is in title format, else returns false.
isupper() Returns true when all characters of the string are in uppercase, else returns false.
join() Joins the elements of an iterable to the end of the string.
ljust() Returns a left justified version of the string.
lower() Converts all characters of the string into lowercase.
lstrip() Returns a left trim version of the string.
maketrans() Returns a mapping table to be used in translations.
partition() Returns a tuple where the string is parted into three parts.
replace() Returns a string where a specified value is replaced with a specified value.
rfind() Searches the string for a specified value and returns the last position of where it was found.
rindex() Searches the string for a specified value and returns the last position of where it was found.
rjust() Returns a right justified version of the string.
rpartition() Returns a tuple where the string is parted into three parts.
rsplit() Splits the string at the specified separator, and returns a list.
rstrip() Returns a right trim version of the string.
split() Splits the string at the specified separator, and returns a list.
splitlines() Splits the string at line breaks and returns a list.
startswith() Returns true if the string starts with the specified value.
strip() Returns a trimmed version of the string.
swapcase() convert all lowercase characters into uppercase and uppercase characters into lowercase.
title() Converts all characters of the string in title format.
translate() Returns a translated version of the specified string.
upper() Converts all characters of the string into uppercase.
zfill() Fills the string with a specified number of 0 values at the beginning.
FunctionsDescription
len() Returns total number of characters in the string.