什么是 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))