The Wayback Machine - http://web.archive.org/web/20240905163200/https://www.geeksforgeeks.org/convert-object-to-string-in-python/
Open In App

Convert Object to String in Python

Last Updated : 28 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting an object to a string.

Converting Object to String

Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.

Example 1: Using str() method

Python3




# object of int
Int = 6
  
# object of float
Float = 6.0
  
# Converting to string
s1 = str(Int)
print(s1)
print(type(s1))
  
s2= str(Float)
print(s2)
print(type(s2))


Output:

6
<class 'str'>
6.0
<class 'str'>

Example 2: Use repr() to convert an object to a string

Python3




print(repr({"a": 1, "b": 2}))
print(repr([1, 2, 3]))
  
# Custom class
class C():
    def __repr__(self):
        return "This is class C"
  
# Converting custom object to 
# string
print(repr(C()))


Output:

{'a': 1, 'b': 2}
[1, 2, 3]
This is class C

Note: To know more about str() and repr() and the difference between to refer, str() vs repr() in Python



Similar Reads

Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 min read
Python Pandas - Convert PeriodIndex object to Timestamp and set the frequency
In this article, we will discuss how to convert period index objects to timestamp and set the frequency in the python programming language. The pandas PeriodIndex.to_timestamp() method is used to convert a PeriodIndex object to Timestamp and set the frequency. frequency can be set using the 'freq' parameter of the method. Example 1: Pandas package
3 min read
How To Convert Generator Object To Dictionary In Python
Generators in Python are powerful constructs for handling large datasets efficiently. However, there may be scenarios where you want to convert the output of a generator into a dictionary for easier manipulation and retrieval of data. In this article, we'll explore five different methods to convert a generator object to a dictionary in Python. Conv
3 min read
Convert Generator Object To JSON In Python
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used methods. Convert Generator Object To JSON In PythonBelo
2 min read
How To Fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python
In this article, we'll delve into understanding of typeerror and how to fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python. Types of Errors in Python Script ExecutionThere are many different types of errors that can occur while executing a python script. These errors indicate different meanings and are typically classified in
3 min read
Convert Generator Object To List in Python
Python, known for its simplicity and versatility, provides developers with a plethora of tools to enhance their coding experience. One such feature is the generator object, which allows for efficient iteration over large datasets without loading them entirely into memory. In this article, we'll explore the methods behind converting generator object
3 min read
Convert from '_Io.Bytesio' to a Bytes-Like Object in Python
In Python, converting from _io.BytesIO to a bytes-like object involves handling binary data stored in a BytesIO object. This transformation is commonly needed when working with I/O operations, allowing seamless access to the raw byte representation contained within the BytesIO buffer. Various methods can be used to Convert From '_Io.Bytesio' To A B
2 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Convert Django Model Object to Dict with all of the Fields Intact
Django, a high-level Python web framework, simplifies the process of building web applications by providing a robust ORM (Object-Relational Mapping) system. Often, while developing web applications, there arises a need to convert Django model instances into dictionaries, retaining all the fields intact. This conversion is useful for various purpose
4 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Convert binary to string using Python
Data conversion has always been widely used utility and one among them can be the conversion of a binary equivalent to its string. Let’s discuss certain ways in which this can be done. Method #1:The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is
4 min read
Convert date string to timestamp in Python
The Most Common way we use to store dates and times into a Database is in the form of a timestamp. date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are: Using timetuple()U
2 min read
Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the "%s" keyword, the .format function or using f-string function. Below is the list
3 min read
Convert string to title case in Python
Title case is a style of writing that is used for the titles of articles, books, movies, and other works. The rules for writing in title case are: 1) Always capitalize the first word. 2) Capitalize all words except the following parts of speech: articles - a, an, the coordinating conjunctions - and, but, for, nor, or, so, yet short prepositions - t
2 min read
How to convert string to integer in Python?
In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer. Syntax : int(string, base)
3 min read
Convert String to Long in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long. Converting String to long A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Py
1 min read
Convert Decimal to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string. Converting Decimal to String str() method can be used to convert decimal to string in Python. Syntax: str(object, encoding=’utf-8?, errors=’strict’) Parameters: object: The obj
1 min read
Convert Python String to Float datatype
Let us see how to convert a string object into a float object. We can do this by using these functions : float() decimal() Method 1: Using float() # declaring a string str1 = &quot;9.02&quot; print(&quot;The initial string : &quot; + str1) print(type(str1)) # converting into float str2 = float(str1) print(&quot;\nThe conversion of string to float i
2 min read
Convert String to Set in Python
We can convert a string to setin Python using the set() function. Syntax : set(iterable) Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument. Example 1 : C/C++ Code # create a string str string = &amp;quot;geeks&amp;quot; pri
2 min read
Convert Set to String in Python
In this article, we will discuss how to convert a set to a string in Python. It can done using two ways - Method 1: Using str() We will convert a Set into a String in Python using the str() function. Syntax : str(object, encoding = ’utf-8?, errors = ’strict’) Parameters : object : The object whose string representation is to be returned.encoding :
3 min read
How to Convert Bytes to String in Python ?
In this article, we are going to cover various methods that can convert bytes to strings using Python. Convert bytes to a string Different ways to convert Bytes to string in Python: Using decode() methodUsing str() functionUsing codecs.decode() methodUsing map() without using the b prefixUsing pandas to convert bytes to strings Data types are the c
3 min read
Python - Convert Image to String and vice-versa
To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available. Convert Image To StringHere First We Import "Base64" Method To Encode
2 min read
Article Tags :
Practice Tags :