杰瑞科技汇

Python object str 是什么?如何转换?

Of course! This is a fundamental concept in Python. Let's break down what the str object is, how it works, and why it's so important.

Python object str 是什么?如何转换?-图1
(图片来源网络,侵删)

What is a str Object?

In Python, a str (short for string) is an immutable sequence of characters.

Let's unpack that:

  • Object: In Python, everything is an object. A string is a specific type of object that has its own properties (like its length) and methods (like .upper() or .find()).
  • Sequence: A string is an ordered collection of characters. You can access individual characters by their position (index), you can loop through them, and you can slice them.
  • Immutable: This is a crucial concept. Once a string is created, it cannot be changed. Any operation that seems to "modify" a string actually creates a new string object.

Creating a String

You can create strings using either single quotes (), double quotes (), or triple quotes ( or ).

# Single quotes
name = 'Alice'
# Double quotes
message = "Hello, World!"
# Triple quotes (useful for multi-line strings)
description = """
This is a longer string
that spans multiple lines.
"""
# You can also use the str() constructor to convert other types to a string
number_as_string = str(123)
print(number_as_string)  # Output: '123'

Key Characteristics and Operations

A. Immutability in Action

This is the most important concept to understand about strings.

Python object str 是什么?如何转换?-图2
(图片来源网络,侵删)
my_string = "hello"
# This will FAIL with an error, because strings are immutable.
# You cannot change a character in place.
# my_string[0] = "H"  # TypeError: 'str' object does not support item assignment
# To "change" a string, you create a new one.
new_string = "H" + my_string[1:]
print(new_string)  # Output: 'Hello'
print(my_string)   # Output: 'hello' (The original string is unchanged)

B. Common Operations

Operation Description Example Output
Concatenation Joining two strings with "hello" + " world" 'hello world'
Repetition Repeating a string with "ha" * 3 'hahaha'
Indexing Getting a character by its position (starts at 0) greeting[0] 'H'
Slicing Getting a substring from start to end (end is exclusive) greeting[0:5] 'Hello'
Length Getting the number of characters with len() len(greeting) 13
greeting = "Hello, World!"
# Indexing
print(f"First character: {greeting[0]}")
print(f"Last character: {greeting[-1]}") # Negative index counts from the end
# Slicing
print(f"First 5 characters: {greeting[0:5]}")
print(f"From index 7 to the end: {greeting[7:]}")
print(f"Everything except the last character: {greeting[:-1]}")

C. Common Methods (Functions belonging to the string object)

Strings have a rich set of built-in methods for manipulation.

Method Description Example
.upper() Converts to uppercase "python".upper() -> 'PYTHON'
.lower() Converts to lowercase "PYTHON".lower() -> 'python'
.strip() Removes leading/trailing whitespace " hello ".strip() -> 'hello'
.split() Splits string into a list of substrings "a,b,c".split(',') -> ['a', 'b', 'c']
.join() Joins a list of strings into one '-'.join(['a', 'b', 'c']) -> 'a-b-c'
.find() Finds the first index of a substring "hello world".find("world") -> 6
.replace() Replaces a substring with another "hello world".replace("world", "python") -> 'hello python'
.startswith() / .endswith() Checks if the string starts/ends with a substring "hello".startswith("he") -> True
.isalpha() / .isdigit() Checks if all characters are letters/digits "123".isdigit() -> True
text = "  Python is Fun!  "
# Using methods
print(text.strip())               # 'Python is Fun!'
print(text.lower())               # '  python is fun!  '
print(text.replace("Fun", "Awesome")) # '  Python is Awesome!  '
print(text.split())               # ['Python', 'is', 'Fun!'] (splits on whitespace by default)

f-Strings: The Modern Way to Format Strings

f-strings (formatted string literals) are the preferred and most readable way to embed expressions inside string literals. They were introduced in Python 3.6.

You simply put an f before the opening quote and use curly braces to place your variables or expressions inside the string.

name = "Bob"
age = 30
product = "Python Course"
price = 99.99
# Before f-strings, this was done with .format() or % formatting
# Old way: "Hello, %s. You are %d years old." % (name, age)
# Older way: "Hello, {}. You are {} years old.".format(name, age)
# Modern f-string way
message = f"Hello, {name}. You are {age} years old."
print(message)
# You can also put expressions inside the braces
total = f"The total for your {product} is ${price * 1.08:.2f}" # .2f formats to 2 decimal places
print(total)

Output:

Python object str 是什么?如何转换?-图3
(图片来源网络,侵删)
Hello, Bob. You are 30 years old.
The total for your Python Course is $107.99

The __str__() vs. __repr__() Methods

When you create your own custom objects, you can define how they should be represented as a string. This is done with two special "dunder" (double underscore) methods:

  • __str__(self): The "user-friendly" string representation. It's meant to be readable and is used by print() and str(). If __str__ is not defined, Python will fall back to __repr__.
  • __repr__(self): The "developer-friendly" or "official" string representation. It's meant to be unambiguous and, ideally, could be used to recreate the object. It's used by the interactive console and repr().

Example:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    # The user-friendly representation
    def __str__(self):
        return f"'{self.title}' by {self.author}"
    # The developer representation
    def __repr__(self):
        return f"Book(title='{self.title}', author='{self.author}')"
# Create an instance
my_book = Book("The Hobbit", "J.R.R. Tolkien")
# See the difference
print(my_book)          # Calls __str__()
print(repr(my_book))     # Calls __repr__()

Output:

'The Hobbit' by J.R.R. Tolkien'The Hobbit', author='J.R.R. Tolkien')

Summary

Concept Description
What it is An immutable sequence of characters.
How to create Using , , , or str(...).
Key Feature Immutability: Strings cannot be changed after creation.
Core Operations Indexing, slicing, concatenation (), repetition ().
Essential Methods .upper(), .lower(), .strip(), .split(), .find(), .replace().
Modern Formatting f-strings (f"...") are the standard for embedding variables.
Custom Objects Define __str__() for user output and __repr__() for developer output.
分享:
扫描分享到社交APP
上一篇
下一篇