Оператор str в python

Оператор str в python

The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.

Strings are immutable sequences.

Constructors¶

str() Returns a string containing a printable representation of an object. x”string” (string designators) Returns a modified string. literal syntax Initializes a new instance of the str type.

Methods¶

Searching¶

find Returns the index of the first occurrence of the string searched for. rfind Returns the index of the last occurrence of the string searched for. index Returns the index of the first occurrence of the string searched for (raises ValueError if not found). rindex Returns the index of the last occurrence of the string searched for (raises ValueError if not found).

Replacing¶

replace Returns a copy of the string with a specified substring replaced specified number of times. translate Returns a copy of the string with characters mapped through the given translation table or deleted.

Leading and Trailing Characters¶

lstrip Returns a copy of the string with leading characters removed. rstrip Returns a copy of the string with trailing characters removed. strip Returns a copy of the string with leading and trailing characters removed.

Splitting and Joining¶

split Returns a list of the words in the string, separated by the delimiter string. rsplit Returns a list of the words in the string, separated by the delimiter string (starting from right). partition Returns a tuple containing the first part of the string split by the specified separator, the separator itself and the other part of the string. rpartition Returns a tuple containing the first part of the string split by the specified separator, the separator itself and the other part of the string (starting from right). splitlines Returns a list of the lines in the string, breaking at line boundaries. join Returns a string made from the elements of an iterable.

Читайте также:  Выполнить задачи на питоне

Changing Case¶

upper Returns a copy of the string in UPPER CASE. lower Returns a copy of the string in lower case. capitalize Returns a copy of the string in Capital case. title Returns a copy of the string in Title Case. swapcase Returns a copy of the string with case swapped.

Information¶

count Returns the number of non-overlapping occurrences of a substring in the searched string. startswith Returns a Boolean stating whether a string starts with the specified prefix. endswith Returns a Boolean stating whether a string ends with the specified suffix. isalnum Returns a Boolean stating whether the string contains only letters and digits. isalpha Returns a Boolean stating whether the string contains only letters. isdigit Returns a Boolean stating whether the string contains only digits. islower Returns a Boolean stating whether the string is in lower case. isspace Returns a Boolean stating whether the string contains only whitespace characters. istitle Returns a Boolean stating whether the string is in Title case. isupper Returns a Boolean stating whether the string is in UPPER CASE.

Formatting¶

ljust Returns the string left justified in a string of specified length. rjust Returns the string right justified in a string of specified length. center Returns the string centered in a string of specified length. zfill Returns the numeric string left filled with zeros in a string of specified length. expandtabs Returns a copy of the string where all tab characters were replaced by spaces. `format`_ Returns a formatted version of the string.

Encodings¶

decode Decodes the string using the codec registered for encoding. encode Returns an encoded version of the string.

Functions¶

len Returns an int type specifying number of elements in the collection. min Returns the smallest item from a collection. max Returns the largest item in an iterable or the largest of two or more arguments. cmp Compares two objects and returns an integer according to the outcome. sorted Returns a sorted list from the iterable. reversed Returns a reverse iterator over a sequence. all Returns a Boolean value that indicates whether the collection contains only values that evaluate to True. any Returns a Boolean value that indicates whether the collection contains any values that evaluate to True. enumerate Returns an enumerate object. zip Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. chr Returns a string of one character whose ASCII code is the specified number. ord Returns an integer representing the code of the character. unichr Returns a Unicode character specified by the code. `format`_ Returns a formatted string.

Читайте также:  Телеграм бот рассылка php

Operators¶

`% (string formatting)`_ Formats the string according to the specified format. [] (index operator) Gives access to a sequence’s element. [::] (slicing) Gives access to a specified range of sequence’s elements. + (concatenation) Returns a concatenation of two sequences. * (multiple concatenation) Returns a sequence self-concatenated specified amount of times.

Источник

str() in Python

Python Certification Course: Master the essentials

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.
Читайте также:  How to increase array size java

Example of str() in Python

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

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.

What is 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:

. 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.

Let us provide a different encoding standard.

Conclusion

  • To convert a specified value or any 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 casting or type conversion.
  • The str in python takes three parameters and returns an equivalent string object. Its syntax is: str(object, encoding = ‘utf-8’, errors = ‘strict’) .
  • The object parameter is required but the encoding and errors parameters are optional.

Read More:

Источник

Оцените статью