Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Python String and Methods tutorial

Python string format

Python string is one of the fundamental data types in python and string is a sequence of Unicode characters enclosed within (single or double) quotes. Each character in a string is based upon a Unicode character. In Python, the built-in str class represents strings based upon the Unicode international character set, a 16-bit character encoding that covers most written languages.

In any application, we have used string data from a text input box or reading string from a file, etc.

In this tutorial, we’ll learn Python string data type, its str class, how strings are stored inside memory, and some example of python string methods available on str class. Let’s get started.

What is Python string data type?

In Python, strings are immutable data, this means the programmer cannot modify the contents of the string object (even by mistake).

name = 'edupala';
name = 'Edupala site';

Although this might seem like the above statement 2 modified name string object but not, assigning a new value to the variable will create a completely new object. 

How to create a string?

Use quotes, either single quotes or double quotes to create string literals. Enclosing characters inside single or double quotes will create a string. We can even use triple quotes to create strings with multiple lines.

#Single quote 
name = 'edupala';

#Double quote 
message = "Hello world";
print(name +' from ' + message );

#Triple quote
description = """Python is 
           OO language"""
python string example
python string example

Here we have listed some of the properties of string.

  1. Strings are created using single or double quotes only.
  2. Strings have a length, defined as the number of characters inside a string.
  3. Character in a string can access using an index as string characters are stored contiguously in memory.

We can use single and double quotes of a string containing few characters, but if the string has long or multiple lines then we either have used one of two ways.

  1. Break the string up across multiple lines by putting a backslash () at the end of each line except the last.
  2. using triple quotes is a better way of handling string with multiple lines.
str1 = "Lorem ipsum dolor sit amet consectetur adipisicing elit.\
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum \
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium\
optio, eaque rerum! Provident similique accusantium nemo autem. 

#Better approach of using multiple lines triple quote

str2 = """Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum! Provident similique accusantium nemo autem."""
Accessing Character in string

In our previous python variable tutorial, we have seen data types like list, tuple, and str class support indexing. There is a commonality between these classes, each data type supports indexing to access individual elements in sequences. As in Python, everything is an object or class, these classeshr are significant differences in the way class represents internally.

name = '';
# Give ouput E

#Give output com

We can access a character in a string using its index and the index always start with the value 0 and increment by one.

In the above line, I created a string Hello world and stored it in a variable called s. Abstractly, we can visualize this as it is represented inside memory as shown below.

Python string methods

String in Python are objects, it has a set of available methods that we can use to perform operations on a string. Here we list some of the python string methods.

str = ''
String method nameDescription
str.lower()Return string in lower case.
str.upper()Return string in upper case.
str.strip()Return string with removed whitespace at start and end.
str.find(‘com’)Return offset or index of a substring in a string object, if not found then return -1.
str.startswith(‘edu’)Return boolean value true if a string starts with the search word, false if not.
str.endswith(‘com’) Return boolean value true if a string end with the search word, false if not.
str.replace(‘ed’, ‘EDU’)Replace first argument with second.
str.split(‘delim’)  eg str.split(‘,’)Return list of substring by comma
str.isalpha()Return boolean true or false, isaplha test if the string is alphabetic.
str.isdigit()Return boolean true or false, isdigi test if a string is a digit.
str.join()Join the string from the list string, separated by a string separator.
str.capitalize()Make first character capital letter.
Python string methods

In the above table, I had listed some of the most common using string methods, python3 also has many more methods, I have listed a few here.

str.ljust(width [, fill]) [, fill]) 
str.count(sub [, start [, end]]) 
str.encode([encoding [,errors]]) 
str.maketrans(x[, y[, z]])
str.endswith(suffix [, start [, end]]) 
str.replace(old, new [, count])
str.find(sub [, start [, end]]) 
str.rfind(sub [,start [,end]])
str.format(fmtstr, *args, **kwargs) 
str.rindex(sub [, start [, end]])
str.index(sub [, start [, end]]) 
str.rjust(width [, fill])
str.rsplit([sep[, maxsplit]])
str.split([sep [,maxsplit]])
str.startswith(prefix [, start [, end]])

Example of Python string methods.

Python string method
Python string method

What is Python string format?

Python has a robust formatting system for strings and we can format strings using the following ways.

  1. using f-string
  2. using format() method
  3. % Operator

String formatting is the process of inserting a custom string or variable in predefined text. Let’s demonstrate the Python string format using f-string, which was introduced in Python 3.6.

age = 20;
print(f"My name is {name}, I'm {age}");

My name is edupala, I'm 20

string format specifiers to allow you to include numbers, and strings in your strings, and we can format those numbers in strings with different styles.

Python string formatting using format method

We can use the format method for string formatting, here is an example of it.

print("{0} {3} {1} {2}".format('Edupala', 'learning', 'code', 'for'));

Edupala for learning code

We can use a curly brace and number to align the string position.

Python string formatting using the format % operator

The % operator is used in a programming language like C, we can use the same here in Python.

age = 20;
print('%s=%s' % (name, age)) 


We can use the following symbol for string formatting.

Format SymbolDescription
%dDecimal integers, eg
%oOctal number
%iSign integer
%uUnsigned decimal.
%x or %XHexadecimal lowercase
%e or %EExponential notation
%%A percent sign
%rRepr format (debugging format).
%sString format.
%f or %FFloating-point real number.
%gEither %f or %e, whichever is short
Python string format

Let’s demonstrate formatting numbers using the % operator.

print('The value of pi is: %2.3f' %(3.141592));

The value of pi is: 3.142, number having three decimal

print('{0:X}, {1:o}, {2:b}'.format(200, 200, 200))
C8, 310, 11001000 (x hexadecimal, o octal b for binnary

str = "Edupala{:<4} blogging for programming"
#Outpu blogging for programming
Insert .com and set available of 4 space for .com

Python also supports the following string formatting

  1. :< Forces the field to be left-aligned within the available space
  2. :> Forces the field to be right-aligned within the available space
  3. :^ Center aligns the result within the available space
  4. := Places the sign in the left-most position
  5. :, Comma as a thousand separator
  6. :_ Underscore as a thousand separator
  7. :b Binary format
  8. :+ Plus sign to indicate if the value is positive or negative
  9. :- Minus sign for negative values
#Use comma as a thousand separator:

num = "Amount collected  {:,}"

Finally, we have completed the Python string and how strings are formatted in python. I hope you liked this tutorial, please consider it sharing with others.

Python String and Methods tutorial

Leave a Reply

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

Scroll to top