EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Python String Operations

Home » Software Development » Software Development Tutorials » Python Tutorial » Python String Operations

Python String Operations

Introduction to Python String Operations

A Python String is a sequence of characters. Python Strings are immutable, it means once we declare a string we can’t modify it. Python provides a built-in class “str” for handling text as the text is the most common form of data that a Python program handles. Following are the common string operations that can be performed in Python:

  • Concatenation of two or more strings.
  • Extracting or slicing partial strings from string values.
  • Adding or removing spaces.
  • Converting to lower or upper case.
  • Formatting strings using string formatters.
  • Finding and/or replacing a text in the given string with some other text.

And the list of operations is countless. Python provides several built-in methods that let us to perform operations on a string in a flexible way.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Examples of String Operations in Python

String Operations can be done in three ways:

  1. Using f-strings
  2. By format() method
  3. Using % operator

Example #1

# String formatters in Python
# String formatting using f-strings
print("<-------------Example 1-------------------->")
print("Enter your name")
name = input()
print(f"Hey !! {name}, welcome to the party...")
print('\n')
print("<-------------Example 2-------------------->")
print("Enter first number")
a = int(input())
print("Enter second number")
b = int(input())
print(f"sum of {a} and {b} is {a+b}")
print('\n')
# String formatting using format() method
print("<--------Default order------------>")
str1 = "{} {} {}".format("Travelling", 'is', 'life')
print("String will be printed in default order:")
print(str1)
print("<--------Positional formatting------------>")
str2 = "{1} {2} {0}".format("love", "Travelling", "is")
print(str2)
print("<--------Keyword formatting------------>")
str3 = "{T} {i} {l}".format(T='Travelling', l='love', i= 'is')
print(str3)
print('\n')
# String formatting using % operator
print("Enter number of items")
item = int(input())
print("%s is carrying %d items"%(name, item))

Output:

Python String Operations Example 1

Explanation:

1. f-string: Letter “f” is placed before the beginning of the string, and the variables mentioned in curly braces will refer to the variables declared above. For example {name} refers to the name variable defined above. Similarly {a} and {b} refers to variable a and b respectively.

2. format() method: format() method is called on a string object. Inside the string we use curly braces {} that will refer to the format() method arguments. Number of {} should match number of arguments inside format()

  • In default formatting {} will refer to the format() arguments in the order in which they are placed.
  • In positional formatting order is indicated inside {}. Above example “{1} {2} {0}”.format(“love”, “Travelling”, “is”) states that argument positioned at index 1 (“travelling”) inside format() will come first, argument position at 2 index(“is”) will come second and argument positioned at index 0(“love”) will come last.
  • In keyword formatting, certain keywords are used inside {} which will be mapped to corresponding format() arguments.

3. % operator: “%” operator will be replaced by variables defined in parenthesis/in tuple. %s means a string variable will come to this place, %d is an integer, %f is a floating-point value.

Example #2

# String methods Part 1
string = "Various string methods"
string2 = "  investment in learning       "
print("lower()")
print(string.lower())
print("upper()")
print(string.upper())
print("islower()")
print(string.islower())
print("isupper()")
print(string.isupper())
print("startswith")
print(string.startswith("Var"))
print("endswith()")
print(string.endswith("el"))
print("join()")
print('-->'.join(['various', 'strings', 'methods']))
print("split()")
print(string.split())
print("ljust()")
print("hello".ljust(15, '*'))
print("rjust(*)")
print("hello".rjust(15, '*'))
print("center()")
print("welcome".center(20, '*'))
print("strip()>")
print(string2.strip())
print("lstrip()")
print(string2.lstrip())
print("rstrip()")
print(string2.rstrip())

Popular Course in this category
Python Training Program (36 Courses, 13+ Projects)36 Online Courses | 13 Hands-on Projects | 189+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.8 (8,353 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)Angular JS Training Program (9 Courses, 7 Projects)

Output:

Python String Operations Example 2

Explanation:

  • lower(): Converts a string to the lowercase letter.
  • upper(): Converts a string to the uppercase letter.
  • islower() / isupper(): Checks if the whole string is in lower case or upper case and returns bool value respectively.
  • startswith(): Returns a bool value. Check if the given string starts with a particular text.
  • endswith(): Returns a bool value. Check if the given string ends with a particular text.
  • join(): Join different strings to make a single concatenated string. A list of strings is joined together into a single string.
  • split(): Reverse of join(). It splits a large string into smaller strings. By default string is split wherever characters such as space, tab or newline characters are found. However a delimiter can be passed inside split(). String then will split when this delimiter is encountered.
  • ljust()/ rjust()/ center(): These three methods are for justifying text. The first argument is an integer length for the justified string and the second argument is the fill character. ljust() fills the fill char on the left side, rjust() fills the fill char on the right side, and center() justifies the text at the center, filling the fill char at both left and right sides.
  • strip()/ lstrip()/ strip(): Removes whitespaces(space, tab and newline) from left side(lstrip()), right side(rstrip()) and from both sides(strip()).

Example #3

# String methods --> Part 2
string = "object oriented programming"
print("Given string :", string)
print('index()')
print("index of 'r' in:'", string, "':", string.index('r'))
print('count()')
print("number of 'o' in '", string, "':", string.count('o'))
print('find()')
print("index of 'z' in '", string, "':", string.find('z'))
print('replace()')
print("replacing 'e' with '3' :", string.replace('e', '3'))

Output:

Python String Operations Example 3

Explanation:

  • index(): index() method finds the first occurrence of a particular character or text in the given string. In this example, the index position for the first occurrence of ‘r’ is printed.
  • count(): counts the total number of occurrences of a character in the given string. Character ‘o’ occurs thrice in the string “object-oriented programming”
  • find(): find() method is similar to index() method. It also returns the index for the first occurrence. But the major difference is that if a character whose index is to find is not present, index() will throw an error while find() returns -1 (as shown in the output)
  • replace(): It replaces a text with another text in the given string. In this example, ‘e’ is being replaced by ‘3’.

Conclusion

Text is the most common form of data a Python program has to operate on. Therefore, Python provides a comprehensive list of string methods that helps the user to perform various operations on strings (bits of text) in a much flexible way without writing the bulk of code.

Recommended Articles

This is a guide to Python String Operations. Here we discuss the different string methods to perform various operations on a string in python along with an example and its code implementation. You can also go through our other related articles to learn more –

  1. Python Compare Strings
  2. Python List Functions
  3. Python Trim String
  4. Python Generators

Python Training Program (36 Courses, 13+ Projects)

36 Online Courses

13 Hands-on Projects

189+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

4 Shares
Share
Tweet
Share
Primary Sidebar
Python Tutorial
  • Function
    • Python Built-in Functions
    • Math Functions in Python
    • Python String Functions
    • Trigonometric Functions in Python
    • Python Input Function
    • Python Input String
    • Python String Operations
    • Python Stream
    • Python Multiline String
    • Python Regex
    • Python Regex Tester
    • Python regex replace
    • Python File Methods
    • Python Import CSV
    • Python Read CSV File
    • Python write CSV file
    • Python Delete File
    • Python File readline
    • Python if main
    • Python Main Method
    • List Method in Python
    • Python List Length
    • Recursive Function in Python
    • Copy List in Python
    • Python Range Function
    • Python Substring
    • Python list remove()
    • Python List Index
    • Python Set Function
    • Python len Function
    • Python eval()
    • Python Counter
    • ord Function in Python
    • strip Function in Python
    • Split Function in Python
    • Python Round Function
    • Python Map Function
    • Python String Join
    • Python format() Function
    • Python Contextlib
    • Python Compare Strings
    • Python Return Value
    • Python List count
    • Filter in Python
    • Python Slice String
    • Python Absolute Value
    • Python Trim String
    • Python Type Function
    • Lowercase in Python
    • Python xrange
    • Python yield
    • Python Find String
    • Max Function in Python
    • Python Power Function
    • pop() in Python
    • Python argparse
    • Python Pickle
    • Python Zip Function
    • Python Split String
    • super() in Python
    • Python Extend
    • Python String Replace
    • Python PEP8
    • Python Filter Function
    • Python if then else
    • Lambda in Python
    • Python BeautifulSoup
    • Python Sleep
    • Python Function Generator
    • Python @classmethod decorator
    • Python Endswith
    • Python BufferedReader
    • Python Async
    • Python Parser
    • Python SystemExit
    • Python pip
    • Python kwargs
  • Basics Part I
    • Introduction To Python
    • What Is Python
    • Careers in Python
    • Advantages of Python
    • Uses of Python
    • Python Features
    • Python Fast And python psyco
    • Python ImportError
    • Benefits and Limitations of Using Python
    • What can I do with?Python
    • Is Python a scripting language
    • Is Python Object Oriented
    • Is Python Open Source
    • Python Socket Programming
    • Useful Tips on Python Programming
    • Python You Should Be Using It
    • Python Web Development
    • Python Programming Beginners Tutorails
    • Practical Python Programming for Non-Engineers
    • Python Programming for the Absolute Beginner
    • Versions of?Python
  • Basic Part II
    • Comments in Python
    • Finally in Python
    • Python Multiline Comment
    • Python Data Types
    • Python Variables
    • Python Variable Types
    • Python Global Variable
    • Python Variable Scope
    • Python Private Variables
    • Python Default Arguments
    • Python Command-line Arguments
    • Indentation in Python
    • Object in Python
    • Python Keywords
    • Python Literals
    • Pointers in Python
    • Iterators in Python
    • Python User Input
    • Python Enumerate
    • Python Commands
    • Type Casting in Python
    • Python Identifiers
    • Python Constants
    • What is NumPy in Python?
    • Cheat Sheet Python
  • Frameworks
    • Python Frameworks
    • Python Compilers
    • Python Editors
    • Best Compiler for Python
    • Python IDE for Windows
    • Python IDE on Linux
  • Installation
    • How To Install Python
    • Install Python on Linux
    • Install Python on Windows
    • Install Anaconda Python
  • Operator
    • Python Operators
    • Arithmetic Operators in Python
    • Python Comparison Operators
    • Logical Operators in Python
    • Assignment Operators in Python
    • Unary Operators in Python
    • String Operators in Python
    • Boolean Operators in Python
    • Identity Operators in Python
    • Python Bitwise Operator
    • Python Remainder Operator
    • Python Modulus Operator
  • Control Statement
    • Conditional Statements in Python
    • Control Statements in Python
    • If Condition in Python
    • If Statement in Python
    • If Else Statement in Python
    • else if Statement in Python
    • Nested IF Statement in Python
    • Break Statement in Python
    • Python Switch Statement
  • Loops
    • Loops in Python
    • For Loop in Python
    • While Loop in Python
    • Do While Loop in Python
    • Python Nested Loops
    • Python Infinite Loop
    • Python Event Loop
  • Sorting
    • Sorting in Python
    • Sorting Algorithms in Python
    • Bubble Sort in Python
    • Merge Sort in Python
    • Heap Sort in Python
    • Quick Sort in Python
    • Python Sorted Function
  • Array
    • Arrays in Python
    • 2D Arrays In Python
    • 3d Arrays in Python
    • Multidimensional Array in Python
    • Python Array Functions
    • String Array in Python
    • Python Sort Array
    • Python Array Length
  • Inheritance
    • Inheritance in Python
    • Single Inheritance in Python
    • Multiple Inheritance in Python
    • Interface in Python
  • Exception
    • Python Exception Handling
    • Custom Exception in Python
    • Indentation Error in Python
    • Python IOError
    • Python EOFError
    • Python NotImplementedError
    • Python TypeError
    • Python ValueError
    • Python AssertionError
    • Python Unicode Error
    • Python NameError
    • Python StopIteration
    • Python OverflowError
    • Python KeyboardInterrupt
  • Advanced
    • Scope in Python
    • Python Collections
    • Constructor in Python
    • Destructor in Python
    • Python Overloading
    • Overriding in Python
    • Function Overloading in Python
    • Method Overloading in Python
    • Operator Overloading in Python
    • Method Overriding in Python
    • Encapsulation in Python
    • Static Method in Python
    • Assert in Python
    • Python References
    • Python Virtualenv
    • Python mkdir
    • Logistic Regression in Python
    • Dictionary in Python
    • Regular Expression in Python
    • Python Import Module
    • Python OS Module
    • Python Sys Module
    • Python Generators
    • Abstract Class in Python
    • Python File Operations
    • Sequences in Python
    • Stack in Python
    • Queue in Python
    • Tuples in Python
    • Python Magic Method
    • Python Sets
    • Python Set Methods
    • Priority Queues in Python
    • Reverse Engineering with Python
    • String Formatting in Python
    • Python isinstance
    • String Length Python
    • Python Concurrency
    • Python List
    • Python Initialize List
    • Python Unique List
    • Python Sort List
    • Python Reverse List
    • Python Empty List
    • List Comprehensions Python
    • List Operations in Python
    • Python Database Connection
    • Python SQLite
    • Python SQLite Create Database
    • Send Mail in Python
    • Bash Scripting and Python
    • Violent Python Book
    • NLP in Python
    • Matplotlib In Python
    • Gray Hat Python: Security
    • Python Subprocess
    • Python Threading Timer
    • Python Threadpool
    • Python Statistics Module
    • How to Call a Function in Python?
    • Python Curl
    • JSON in Python
    • Python json.dumps
    • Python Turtle
    • Python Unit Test
    • pass Keyword in Python
    • Tokenization in Python
    • Random Module in Python
    • Python Multiprocessing
    • Python getattr
    • Collection Module in Python
    • Print Statement in Python
    • Python Countdown Timer
    • Python Context Manager
    • File Handling in Python
    • Python Event Handler
    • Python Print Table
    • Python Docstring
    • Python Dictionary Keys
    • Python Iterator Dictionary
    • Python Class Attributes
    • Python Dictionary Methods
    • Namedtuple Python
    • Namedtuple Python
    • Namedtuple Python
    • Python Class Constants
    • Python Validation
    • Python Switch Case
    • Python Rest Server
    • Python Yield vs Return
    • Python Pickle vs JSON
  • Tkinter
    • Tkinter Widgets
    • Python Tkinter Button
    • Python Tkinter Canvas
    • Tkinter Frame
    • Tkinter LabelFrame
    • Python Tkinter Label
    • Tkinter Scrollbar
    • Tkinter Listbox
    • Tkinter Spinbox
    • Tkinter Checkbutton
    • Tkinter Menu
    • Tkinter Menubutton
    • Tkinter OptionMenu
    • Tkinter Messagebox
    • Tkinter Grid
    • Python Tkinter Entry
    • Tkinter after
    • Tkinter Colors
    • Tkinter Font
    • Tkinter PhotoImage
    • Tkinter TreeView
    • Tkinter Notebook
    • Tkinter Bind
    • Tkinter Icon
    • Tkinter Window Size
    • Tkinter Color Chart
    • Tkinter Slider
    • Tkinter Calculator
  • Programs
    • Patterns in Python
    • Star Patterns in Python
    • Swapping in Python
    • Factorial in Python
    • Fibonacci Series in Python
    • Reverse Number in Python
    • Palindrome in Python
    • Random Number Generator in Python
    • Prime Numbers in Python
    • Armstrong Number in Python
    • Strong Number in Python
    • Leap Year Program in Python
    • Square Root in Python
    • Python Reverse String
    • Python Object to String
    • Python Object to JSON
    • Python Classmethod vs Staticmethod
  • Python 3
    • Python 3 Commands
    • Python 3 cheat sheet
  • Interview Question
    • Python Interview Questions And Answers

Related Courses

Python Certification Course

Programming Languages Courses

Angular JS Certification Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Python Training Program (36 Courses, 13+ Projects) Learn More