Python str() Function

Python3 内置函数Python3 Built-in Functions


str()It is one of the most commonly used built-in functions in Python, used to convert other types of data into string type.

String is one of the most commonly used data types in Python,str()The function helps us convert numbers, lists, tuples, etc. into strings, making it convenient for output and concatenation.

Word Meaning: strYesstringAbbreviation of (string).


Basic Syntax and Parameters

str()It is a built-in function that can be called directly.

Syntax Format

str(object)
str(object, encoding)
str(object, errors)

Parameter Description

  • Parameter object:
    • Type: Any object
    • Description: The object to be converted to a string.
  • Parameter encoding(Optional):
    • Type: String
    • Description: Encoding format (e.g., 'utf-8', 'gbk').
  • Parameter errors(Optional):
    • Type: String
    • Description: Error handling method, default is 'strict' (throws exception). Other options: 'ignore', 'replace'.

Function Description

  • Return Value: Returns a string object.
  • Default Behavior: Returns an empty string when called without parameters.""。

Examples

Let's master through examplesstr()the usage.

Example 1: Basic Usage - Converting Various Types

Example

# Convert integer to string
print(str(123))           # Output: 123
print(type(str(123)))     # Output: <class 'str'>

# Convert float to string
print(str(3.14159))       # Output: 3.14159

# Convert boolean to string
print(str(True))          # Output: True
print(str(False))         # Output: False

# Convert list to string
print(str([1, 2, 3]))     # Output: [1, 2, 3]

# Convert tuple to string
print(str((1, 2, 3)))     # Output: (1, 2, 3)

# Convert dictionary to string
print(str({"name": "Tom", "age": 20}))  # Output: {'name': 'Tom', 'age': 20}

# No argument
print(str())              # Output: (blank line)

Expected Output:

123
<class 'str'>
3.14159
True
False
[1, 2, 3]
(1, 2, 3)
{'name': 'Tom', 'age': 20}

Code Explanation:

  1. When numbers are converted to strings, their original numeric representation is preserved.
  2. When booleans are converted to strings, the first letter is capitalized.
  3. Container types such as lists, tuples, and dictionaries are converted to their string representations.

Example 2: String Concatenation

Example

name = "Tom"
age = 20
height = 1.75

# Concatenate after conversion using str()
info = name + " " + str(age) + " years old " + str(height) + " meters"
print(info)  # Output: Tom 20 years old 1.75 meters

# Using f-string (recommended)
info = f"{name} {age} years old {height} meters"
print(info)  # Output: Tom 20 years old 1.75 meters

# Formatted output
print("Name: " + str(name))  # Output: Name: Tom

Expected Output:

Tom 20岁 1.75米
Tom 20岁 1.75米
姓名: Tom

Code Explanation:

  • str()After conversion, you can use the plus sign for string concatenation.
  • Modern Python recommends using f-string for string formatting, which is more concise and readable.

Example 3: Handling Bytes and Encoding

Example

# Convert bytes to string (encoding must be specified)
data = b"Hello"
s = str(data, encoding='utf-8')
print(s)  # Output: Hello

# Handle encoding errors
data = b"Hello\x80"
s = str(data, encoding='utf-8', errors='ignore')
print(s)  # Output: Hello (illegal bytes ignored)

s = str(data, encoding='utf-8', errors='replace')
print(s)  # Output: Hello (replaced with replacement character)

Expected Output:

Hello
Hello
Hello

This example demonstratesstr()the usage when handling bytes and encoding.


Python3 内置函数Python3 Built-in Functions


Other Extensions