TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Str Function Explained in Detail
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Str Function Explained in Detail

Last updated: Dec 27, 2023 9:54 pm
By Meenakshi Agarwal
Share
7 Min Read
Python Str Function Explained
SHARE

In this tutorial, we will delve into the str function in Python to understand its capabilities, usage, and practical applications. Python, being a versatile and user-friendly programming language, offers a plethora of built-in functions that simplify various tasks. One such fundamental function is str, which plays a crucial role in working with strings.

Contents
Basic SyntaxEncoding ParamErrors ParamConvert Different Data Types to Strings1. Convert Numbers to Strings2. Convert Booleans to Strings3. Convert Lists and Tuples to StringsApply Str Function on ClassesFormat Strings with the str FunctionHandle Special Characters and Escape Sequences1. Include Quotes in Strings2. Escape SequencesConvert Strings to Other Data Types1. Convert Strings to Numbers2. Evaluating Expressions in Strings

Understanding the str Function in Python

The str function in Python primarily converts objects into strings. Its main task is to create a human-readable version of data, making it easier to display, print, or manipulate. The function takes an object as an argument and returns its string representation.

Basic Syntax

The basic syntax of the str function in Python is as follows:

str(object, encoding='utf-8', errors='strict')

Here, object can be any Python object that you want to convert to a string. The other parameters: encoding and errors are optional.

Let’s briefly cover these additional parameters:

Encoding Param

The encoding param is for specifying the character encoding of the string. It is useful when dealing with byte sequences.

bitoj = b'Hello, World!'
stroj = str(bitoj, encoding='utf-8')
print(stroj)

Errors Param

The errors param determines what to do with the encoding and decoding errors. It allows you to define the error handling when the given encoding can’t represent a character.

bitoj = b'Hello, World! \x80'  # Contains an invalid byte
stroj = str(bitoj, encoding='utf-8', errors='ignore')
print(stroj)

These additional parameters provide flexibility in handling different encoding scenarios.

Convert Different Data Types to Strings

Let’s understand how to use the Python str function to change from other types to strings.

Also See: Python Convert Strings to Integers

1. Convert Numbers to Strings

The str function can convert numeric values to strings. This is particularly useful when you want to concatenate numbers with other strings or format them in a specific way.

# Example 1: Convert an integer to a string
num = 42
str_num = str(num)
print("The answer is: " + str_num)

# Example 2: Convert a floating-point number to a string
pi = 3.14159
str_pi = str(pi)
print("The value of pi is approximately: " + str_pi)

2. Convert Booleans to Strings

We can use the str function to convert Python boolean values (True or False) to their string representations.

# Example: Converting a boolean to a string
is_python_fun = True
str_boolean = str(is_python_fun)
print("Is Python fun? " + str_boolean)

3. Convert Lists and Tuples to Strings

The str function applies to lists and tuples to obtain their string representations.

# Example 1: Convert a list to a string
fruits = ["apple", "orange", "banana"]
str_fruits = str(fruits)
print("List of fruits: " + str_fruits)

# Example 2: Convert a tuple to a string
colors = ("red", "green", "blue")
str_colors = str(colors)
print("Tuple of colors: " + str_colors)

Must Read: Python Convert List to String

Apply Str Function on Classes

In addition to basic data types, we can define a class and provide a custom string representation by implementing the __str__ method.

After this, when we use the str function on this Python class object, it will the class instance into a string.

class HandsOn:
    def __init__(self, task, length):
        self.task = task
        self.length = length

    def __str__(self):
        return f"{self.task} is {self.length} days long."

# Example: Convert an instance of a custom class to a string
o_task = HandsOn("Coding", 7)
s_task = str(o_task)
print(s_task)

Format Strings with the str Function

The str function can also supplement the Python string format to create formatted strings. This is especially useful when you want to combine variables and strings dynamically.

# Example: Format a simple string using the str function
city = "Vatican"
people = 510
nice_str = str("My city is {} and it hosts {} people.".format(city, people))
print(nice_str)

Handle Special Characters and Escape Sequences

The str function is essential for dealing with special characters and escape sequences in Python.

1. Include Quotes in Strings

To include quotes within a string, you can use the str function to convert the quotes to their string representations.

# Example: Include quotes in a string
quote = "To be or not to be, that is the question."
quote_with_quotes = str('Shakespeare once said: "{}"'.format(quote))
print(quote_with_quotes)

2. Escape Sequences

Escape sequences are characters preceded by a backslash (\) that have a special meaning in strings. The str function helps in handling these escape sequences.

# Example: Using escape sequences with the str function
escaped_str = str("This is a line.\nThis is a new line.\tThis is a tab.")
print(escaped_str)

Convert Strings to Other Data Types

The str function is not only about converting other Python data types to strings but can also turn back converted strings back to their original state.

1. Convert Strings to Numbers

You can use the str function in conjunction with int and float functions to convert string representations of numbers back to numeric types.

# Example 1: Convert a string to an integer
num_str = "42"
num_int = int(num_str)
print("The converted integer is:", num_int)

# Example 2: Convert a string to a float
float_str = "3.14"
float_num = float(float_str)
print("The converted float is:", float_num)

2. Evaluating Expressions in Strings

In certain scenarios, the eval function combined with the str function can be employed to evaluate expressions stored as strings.

# Example: Evaluating an expression stored as a string
expression_str = "3 + 5 * 2"
result = eval(expression_str)
print("The result of the expression is:", result)

Conclusion

In this tutorial, we have explored the str function in Python from various angles. We covered its basic syntax, converting different data types to strings, creating string representations for custom objects, formatting strings, handling special characters, and converting strings back to other data types. The str function proves to be a versatile tool, essential for manipulating and displaying data in a human-readable format. Whether you are working with basic data types or custom classes, mastering the str function is a fundamental step towards becoming proficient in Python programming.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Get the Current Working Directory in Python How to Get the Current Working Directory in Python
Next Article Floor Function in Python with Examples Understanding the Floor Function in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x