今天我们来学习字符串数据类型相关知识,将讨论如何声明字符串数据类型,字符串数据类型与 ASCII 表的关系,字符串数据类型的属性,以及一些重要的字符串方法和操作,超级干货,不容错过!
什么是 Python 字符串
字符串是包含一系列字符的对象。字符是长度为 1 的字符串。在 Python 中,单个字符也是字符串。但是比较有意思的是,Python 编程语言中是没有字符数据类型的,不过在 C、Kotlin 和 Java 等其他编程语言中是存在字符数据类型的
我们可以使用单引号、双引号、三引号或 str() 函数来声明 Python 字符串。下面的代码片段展示了如何在 Python 中声明一个字符串:
# A single quote string
single_quote = 'a' # This is an example of a character in other programming languages. It is a string in Python
# Another single quote string
another_single_quote = 'Programming teaches you patience.'
# A double quote string
double_quote = "aa"
# Another double-quote string
another_double_quote = "It is impossible until it is done!"
# A triple quote string
triple_quote = '''aaa'''
# Also a triple quote string
another_triple_quote = """Welcome to the Python programming language. Ready, 1, 2, 3, Go!"""
# Using the str() function
string_function = str(123.45) # str() converts float data type to string data type
# Another str() function
another_string_function = str(True) # str() converts a boolean data type to string data type
# An empty string
empty_string = ''
# Also an empty string
second_empty_string = ""
# We are not done yet
third_empty_string = """""" # This is also an empty string: ''''''
在 Python 中获取字符串的另一种方法是使用 input() 函数。input() 函数允许我们使用键盘将输入的值插入到程序中。插入的值被读取为字符串,但我们可以将它们转换为其他数据类型:
# Inputs into a Python program
input_float = input() # Type in: 3.142
input_boolean = input() # Type in: True
# Convert inputs into other data types
convert_float = float(input_float) # converts the string data type to a float
convert_boolean = bool(input_boolean) # converts the string data type to a bool
我们使用 type() 函数来确定 Python 中对象的数据类型,它返回对象的类。当对象是字符串时,它返回 str 类。同样,当对象是字典、整数、浮点数、元组或布尔值时,它分别返回 dict、int、float、tuple、bool 类。现在让我们使用 type() 函数来确定前面代码片段中声明的变量的数据类型:
# Data types/ classes with type()
print(type(single_quote))
print(type(another_triple_quote))
print(type(empty_string))
print(type(input_float))
print(type(input_boolean))
print(type(convert_float))
print(type(convert_boolean))
ASCII 表与 Python 字符串字符
美国信息交换标准代码 (ASCII) 旨在帮助我们将字符或文本映射到数字,因为数字集比文本更容易存储在计算机内存中。ASCII 主要用英语对 128 个字符进行编码,用于处理计算机和编程中的信息。ASCII 编码的英文字符包括小写字母(a-z)、大写字母(A-Z)、数字(0-9)以及标点符号等符号
ord() 函数将长度为 1(一个字符)的 Python 字符串转换为其在 ASCII 表上的十进制表示,而 chr() 函数将十进制表示转换回字符串。例如:
import string
# Convert uppercase characters to their ASCII decimal numbers
ascii_upper_case = string.ascii_uppercase # Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
for one_letter in ascii_upper_case[:5]: # Loop through ABCDE
print(ord(one_letter))
Output:
65
66
67
68
69
# Convert digit characters to their ASCII decimal numbers
ascii_digits = string.digits # Output: 0123456789
for one_digit in ascii_digits[:5]: # Loop through 01234
print(ord(one_digit))
Output:
48
49
50
51
52
在上面的代码片段中,我们遍历字符串 ABCDE 和 01234,并将每个字符转换为它们在 ASCII 表中的十进制表示。我们还可以使用 chr() 函数执行反向操作,从而将 ASCII 表上的十进制数字转换为它们的 Python 字符串字符。例如:
decimal_rep_ascii = [37, 44, 63, 82, 100]
f