Что означает str в python
Перейти к содержимому

Что означает str в python

  • автор:

Типы данных в Python

Тип данных определяет, что может храниться внутри переменной. Например:

Здесь 24 (целое число) присваивается переменной num . Таким образом, тип данных num относится к классу int .

Типы данных в Python

Тип данных Класс Описание
Числа int, float, complex Содержит числовые значения.
Строки str Содержит последовательность символов.
Списки list, tuple, range Содержит последовательность элементов.
Словари dict Содержит данные в виде пары ключ-значение.
Логический bool Содержит True или False.
Множество set, frozeenset Содержит последовательность уникальных элементов.

Поскольку в Python всё является объектом, типы данных на самом деле являются классами, а переменные — экземплярами (объектами) этих классов.

Числовые типы данных в Python

Числовой тип данных используется для хранения числовых значений. Целые числа, числа типа с плавающей точкой и составные числа попадают в категорию чисел в Python и определяются как int , float и complex .

int — содержит целые числа со знаком неограниченной длины.

float — содержит числа с плавающей десятичной точкой с точностью до 15 знаков после точки.

Мы можем использовать функцию type(), чтобы узнать, к какому классу принадлежит переменная или значение. Например:

str() in Python

To convert a specified value or an object into a string object, we use str in python. The conversion of one data type into the other data type is known as type conversion or type casting in python.

Syntax of str() in Python

The syntax of the method, str in python is very simple:

The encoding and errors parameters are optional parameters but the object parameter is required.

Parameters of str() in Python

The method — str() in python takes three parameters in which one of which is required and the other two are optional. The parameters provided to the str() in python are:

  • object: The object parameter is a required parameter. The object is any object or value(s) that is to be converted into a string object. If we do not provide any object in the parameter, the str in python returns an empty string.
  • encoding: The encoding parameters stores the encoding of the provided object. If we do not provide any encoding parameter, the default value i.e. UTF-8 is provided.
  • errors: The error stores the specified action that needs to be performed if the conversion or decoding fails. We can simply say that error is the response when decoding fails.

Return Values of str() in Python

The str in python returns the string object value (string version) of the given object or number. If we do not give any parameter in the method, it will return an empty string.

Exceptions of str() in Python

The str in python does not raise an exception in general. But whenever we do not pass any parameter to the str() function, the str function returns an empty string.

There are 6 types of errors that can be provided as a parameter in the str() method.

  • strict: It is the default value for the error parameter, the strict raises a UnicodeDecodeError.
  • ignore: We can specify ignore to ignore the unencoded Unicode.
  • replace: The replace is used to replace the un-encodable Unicode with a question mark (?).
  • xmlcharrefreplace: The xmlcharrefreplace is used to insert XML characters in place of the un-encodable Unicode.
  • backslashreplace: The backslashreplace is used to insert escape sequences ( \uNNNN ) in place of un-encodable Unicode.
  • namereplace: The namereplace is used to insert \N <. >escape sequence in place of un-encodable Unicode.

Example of str() in Python

Let us convert a number into a string object using the method, str in python.

Output:

What is str() in Python?

As we know, the conversion of one data type into the other data type is known as type casting or type conversion. To convert a specified value or an object into a string object, we use str in python.

The str() in python takes three parameters in which one of them is required and the other two are optional. The object parameter is a required parameter. The object is any object or value(s) that is to be converted into a string object. The encoding parameters stores the encoding of the provided object. The error stores the specified action that needs to be performed if the conversion or decoding fails. The str in python returns the string version of the given object or number.

How to use str() in Python?

We can use the str in python to convert an object to a string version of the given object or number. We need to provide the object that needs to be converted into a string. Along with the object, we can also provide the decoding type (like UTF-8) as well as the response took if the decoding fails.

More Examples

Let us take a few examples to understand the str method in python in a better way.

Example 1: Convert to String

Let us take a number and convert it into the string using str in python:

Output:

. <.tip>Note: If we do not provide the error and encoding parameter, the str() method internally calls the __str__() method of the object. In some cases, if the __str__() method is not found, the str() method invokes repr(object) .

Example 2: How str() works for bytes?

Whenever we provide the error and encoding parameter, the object parameter should be of the type: bytes-like-object or bytes or bytes-array.

Let us take an example where we specify the error and encoding parameter to understand the working of str in python in a better way.

str() Built-in Function

Python str() built-in function is used to create a string version of the object that would be passed as argument to it.

In this tutorial, you will learn the syntax of str() function, and then its usage with the help of example programs.

Syntax of str()

The syntax of str() function is

Parameter Description
object [Optional] An object.
encoding [Optional] The encoding to use to generate the string representation of given object.
errors [Optional] Flat that specifies how to handle the encoding errors.

If no object is provided, str() returns an empty string.

Examples

1. Convert list to string

In this example, we will pass list object as argument to str() function. str() function returns string object.

Python Program

Output

2. str() with no argument

In this example, we will pass no argument to the str() function. str() function should return an empty string.

Python Program

Output

3. str() with encoding

Let us use the second form of str() function, and pass encoding as well to the str() function.

Python Program

Output

Summary

In this Python Built-in Functions tutorial, we learned the syntax of str() function, and how to convert any object to its string version using str() function with examples.

Python str()

In this tutorial, you will learn about Python str() with the help of examples.

The str() method returns the string representation of a given object.

Example

str() Syntax

The syntax of str() is:

Here, encoding and errors parameters are only meant to be used when the object type is bytes or bytearray.

str() Parameters

The str() method takes three parameters:

  • object — whose string representation is to be returned
  • encoding — that the given byte object needs to be decoded to (can be UTF-8, ASCII, etc)
  • errors — a response when decoding fails (can be strict, ignore, replace, etc)

Note: There are six types of errors: strict, ignore, replace, xmlcharrefreplace, namereplace, backslashreplace. The default error is strict. ____________________________________________________________________________

str() Return Value

The str() method returns:

  • a printable string representation of a given object
  • string representation of a given byte object in the provided encoding

Example 1: Python() String

Output

In the above example, we have used the str() method with different types of arguments like string, integer, and numeric string.

Example 2: str() with Byte Objects

We can use the str() method with byte objects which are defined by the bytes() method.

In this case, we need to specify the encoding that we want to convert the byte objects to and the type of error checking that the str() method can perform.

Output

In the first example, we have created a byte object b with the string ‘pythön’ and the encoding utf-8 .

We have passed the b object to the str() method and specified the encoding to ascii .

Here, we have set the errors parameter to ignore so, the str() method ignores the character ‘ö’ . Since the method can’t decode this character to ascii , we get the output pythn.

Similarly, in the second example, we’ve set the error to strict . In this case, the str() method will take the character ‘ö’ into account and produce UnicodeDecodeError as the output.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *