30 天 Python 学习 - 第 3 天 - 数据类型 II

2025-06-08

30 天 Python 学习 - 第 3 天 - 数据类型 II

继续昨天学习的字符串数据类型,今天我探索了其他一些特性。

格式化字符串

字符串格式化是一个很巧妙的功能,它允许我们动态更新字符串内容。假设我们从服务器获取了用户信息,并希望根据这些信息显示一条自定义消息。第一个想法是应用字符串连接,例如

first_name = 'Tom'
last_name = 'Cruise'
welcome_message = "Welcome" + " " + first_name + " " + last_name
print(welcome_message) # Welcome Tom Cruise
Enter fullscreen mode Exit fullscreen mode

如果变量较多,动态字符串的可读性可能会略有下降。如果还有其他类型的数据,也需要将其转换为字符串。使用格式化字符串可以更简洁地解决这个问题。

first_name = 'Tom'
last_name = 'Cruise'
welcome_message = f'Welcome {first_name} {last_name}'
print(welcome_message) # Welcome Tom Cruise
Enter fullscreen mode Exit fullscreen mode

字符串前f的 表示格式化字符串。动态值位于{}

这是一种更简洁的语法。JavaScript 中的对应语法是 ES6 中引入的字符串插值或模板字符串。它看起来像这样

firstName = 'Tom';
lastName = 'Cruise';
welcomeMessage = `Welcome ${firstName} ${lastName}`;
console.log(welcomeMessage) // Welcome Tom Cruise
Enter fullscreen mode Exit fullscreen mode

字符串索引

Python 中的字符串只是一些有序的字符集合。因此,我们可以用它实现很多很酷的功能。我们可以很轻松地访问字符串中的字符、选择子字符串、反转字符串等等。这也被称为字符串切片。

language = 'python'
first_character = language[0] # indexing starts from 0
second_character = language[1]
print(first_character) # p
print(second_character) # y
# Strings can be manipulated easily with this syntax [start:stop:step-over]
range_1 = language[0:2] # here it starts from index 0 and ends at index 1
range_2 = language[0::1] # starts at 0, stops at end with step over 1 
range_3 = language[::2] # starts at 0, till end with step 2
range_4 = language[1:] # starts at index 1 till end of string
range_5 = language[-1] # selects last character
range_6 = language[-2] # second last character
reverse_string = language[::-1] # starts from end and reverses the string
reverse_string_2 = language[::-2] # reverses string and skips 1 character

print(range_1) # py
print(range_2) # python
print(range_3) # pto
print(range_4) # ython
print(range_5) # n
print(range_6) # o
print(reverse_string) # nohtyp
print(reverse_string_2) # nhy
Enter fullscreen mode Exit fullscreen mode

https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3

不变性

字符串本质上是不可变的。这意味着字符串的值不能被篡改或更改。

favorite_website = 'dev.to'
favorite_website[0] = 'w'
print(favorite_website) # TypeError: 'str' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

内置字符串函数和方法

Python 有一些内置函数和方法来操作字符串数据类型。函数通常是一个可以独立调用的print() round()操作,而方法只是对象的一部分,可以通过.运算符调用。

quote = 'javascript is awesome'
print(len(quote)) # 21 (len calculates total no of characters)
new_quote = quote.replace('javascript', 'python')
print(new_quote) # python is awesome
capitalize = new_quote.capitalize()
print(capitalize) # Python is awesome
upper_case = new_quote.upper()
print(upper_case) # PYTHON IS AWESOME

print(quote) # javascript is awesome (Note: Strings are immutable!) 
Enter fullscreen mode Exit fullscreen mode

https://www.w3schools.com/python/python_ref_functions.asp

https://www.w3schools.com/python/python_ref_string.asp

布尔值

布尔值如boolpython 中所示,并存储TrueFalse

is_cool = True
is_dirty = False
print(10 > 9) # True 
Enter fullscreen mode Exit fullscreen mode

评论

注释是为了增强代码可读性而编写的语句。在 Python 中,注释的写法是#符号后跟注释。注释会被解释器忽略,只是为了提高代码的可读性。我已经在代码示例中使用它们来打印输出或添加一些注释。按照良好的编程习惯,我们应该像阅读英语一样,尽可能提高代码的可读性,并且只在需要时添加注释,因为过多的注释会导致代码臃肿,适得其反。

# This is not a very useful comment but written just for the sake of demonstration
Enter fullscreen mode Exit fullscreen mode

列表

列表是一种重要的数据类型。它们是对象的有序集合。它也是一种数据结构,指的是一个容器,用于以特定格式组织数据以用于不同用途。它们类似于JavaScript 或其他编程语言中的数组。它们用 表示[ ]。它们可用于将相同或不同类型的数据类型存储在一起。

favorite_languages = ['javascript', 'python', 'typescript']
shopping_cart_items = ['pen','toothbrush', 'sanitizer','eraser']
random_things = ['football', 123, True, 'developer', 777]

first_item = shopping_cart_items[0]
print(first_item) # 'pen'
Enter fullscreen mode Exit fullscreen mode

列表切片

与字符串类似,列表也可以切片。然而,与字符串不同,列表是可变的,这意味着它们的数据可以被更改。

soccer_stars = ['ronaldo', 'messi','ibrahimovic','zidane','beckham']
soccer_stars[0] = 'suarez'
print(soccer_stars) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
range = soccer_stars[0:3]
print(range) # ['suarez', 'messi', 'ibrahimovic']
print(soccer_stars) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
# Note : Slicing lists does not mutate them

clone = soccer_stars[:] # copies the list. Commonly used in Python
print(clone) # ['suarez', 'messi','ibrahimovic','zidane','beckham']
reverse_order = soccer_stars[::-1] # reverses the order of data
print(reverse_order) # ['beckham', 'zidane', 'ibrahimovic', 'messi', 'suarez']
Enter fullscreen mode Exit fullscreen mode

矩阵

列表可以是多维的。我上面提到的列表示例都是一维的。但是,我们可以在列表中嵌套列表。因此,二维列表如下所示

matrix_2 = [[1,3,2], [1,3,2], [2,3,4], [2,3,5]]
first_item = matrix_2[0]
print(first_item) # [1,3,2]
first_item_first_element = matrix_2[0][0] # or first_item[0]
print(first_item_first_element) # 1
Enter fullscreen mode Exit fullscreen mode

类似地,我们可以在列表中嵌套任意数量的列表,从而创建类似于小学数学中矩阵的不同维度矩阵。这种矩阵数据有助于存储图像等复杂数据,并用于机器学习模型。探索它们并详细了解它们的实际应用将会非常有趣。

今天我会休息一下,继续学习 List 的剩余概念,例如它的函数、方法和其他模式,然后学习剩下的数据类型:字典、元组、集合和 None。我对逐步探索这些数据结构非常感兴趣。希望你也觉得它们很酷。我们明天再见!

祝你一切顺利!

鏂囩珷鏉ユ簮锛�https://dev.to/arindamdawn/30-days-of-python-day-3-4gn0
PREV
30 天学习 Python 👨‍💻 - 第 30 天 - 免费 Python 资源
NEXT
网络可访问性——为什么我们应该使用语义 HTML