当前位置:  首页>> 技术小册>> Python合辑3-字符串用法深度总结

什么是 Python 字符串

字符串是包含一系列字符的对象。字符是长度为 1 的字符串。在 Python 中,单个字符也是字符串。但是比较有意思的是,Python 编程语言中是没有字符数据类型的,不过在 C、Kotlin 和 Java 等其他编程语言中是存在字符数据类型的

可以使用单引号、双引号、三引号或 str() 函数来声明 Python 字符串。下面的代码片段展示了如何在 Python 中声明一个字符串:

  1. # A single quote string
  2. single_quote = 'a' # This is an example of a character in other programming languages. It is a string in Python
  3. # Another single quote string
  4. another_single_quote = 'Programming teaches you patience.'
  5. # A double quote string
  6. double_quote = "aa"
  7. # Another double-quote string
  8. another_double_quote = "It is impossible until it is done!"
  9. # A triple quote string
  10. triple_quote = '''aaa'''
  11. # Also a triple quote string
  12. another_triple_quote = """Welcome to the Python programming language. Ready, 1, 2, 3, Go!"""
  13. # Using the str() function
  14. string_function = str(123.45) # str() converts float data type to string data type
  15. # Another str() function
  16. another_string_function = str(True) # str() converts a boolean data type to string data type
  17. # An empty string
  18. empty_string = ''
  19. # Also an empty string
  20. second_empty_string = ""
  21. # We are not done yet
  22. third_empty_string = """""" # This is also an empty string: ''''''

在 Python 中获取字符串的另一种方法是使用 input() 函数。input() 函数允许使用键盘将输入的值插入到程序中。插入的值被读取为字符串,可以将它们转换为其他数据类型:

  1. # Inputs into a Python program
  2. input_float = input() # Type in: 3.142
  3. input_boolean = input() # Type in: True
  4. # Convert inputs into other data types
  5. convert_float = float(input_float) # converts the string data type to a float
  6. convert_boolean = bool(input_boolean) # converts the string data type to a bool

使用 type() 函数来确定 Python 中对象的数据类型,它返回对象的类。当对象是字符串时,它返回 str 类。同样,当对象是字典、整数、浮点数、元组或布尔值时,它分别返回 dict、int、float、tuple、bool 类。现在使用 type() 函数来确定前面代码片段中声明的变量的数据类型:

  1. # Data types/ classes with type()
  2. print(type(single_quote))
  3. print(type(another_triple_quote))
  4. print(type(empty_string))
  5. print(type(input_float))
  6. print(type(input_boolean))
  7. print(type(convert_float))
  8. print(type(convert_boolean))

该分类下的相关小册推荐: