Python 字符串总结,建议收藏!(上)

上一篇 / 下一篇  2022-05-20 10:51:16

  什么是 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]
  for one_decimal in decimal_rep_ascii:
      print(chr(one_decimal))

  Output:
  %
  ,
  ?
  R
  d

  在 ASCII 表中,上述程序输出中的字符串字符映射到它们各自的十进制数。
  字符串属性
  零索引: 字符串中的第一个元素的索引为零,而最后一个元素的索引为 len(string) - 1。例如:
  immutable_string = "Accountability"
  print(len(immutable_string))
  print(immutable_string.index('A'))
  print(immutable_string.index('y'))

  Output:
  14
  0
  13

  不变性: 这意味着我们不能更新字符串中的字符。例如我们不能从字符串中删除一个元素或尝试在其任何索引位置分配一个新元素。如果我们尝试更新字符串,它会抛出 TypeError:
  immutable_string = "Accountability"
  # Assign a new element at index 0
  immutable_string[0] = 'B'

  Output:
  ---------------------------------------------------------------------------
  TypeError                                 Traceback (most recent call last)
  ~\AppData\Local\Temp/ipykernel_11336/2351953155.py in  
        2  
        3 # Assign a new element at index 0
  ----> 4 immutable_string[0] = 'B'
  TypeError: 'str' object does not support item assignment

  但是我们可以将字符串重新分配给 immutable_string 变量,不过我们应该注意它们不是同一个字符串,因为它们不指向内存中的同一个对象。Python 不会更新旧的字符串对象;它创建了一个新的,正如我们通过 ids 看到的那样:
  immutable_string = "Accountability"
  print(id(immutable_string))
  immutable_string = "Bccountability"
  print(id(immutable_string)
  test_immutable = immutable_string
  print(id(test_immutable))

  Output:
  2693751670576
  2693751671024
  2693751671024

  上述两个 id 在同一台计算机上也不相同,这意味着两个 immutable_string 变量都指向内存中的不同地址。我们将最后一个 immutable_string 变量分配给 test_immutable 变量。可以看到 test_immutable 变量和最后一个 immutable_string 变量指向同一个地址
  连接: 将两个或多个字符串连接在一起以获得带有 + 符号的新字符串。例如:
  first_string = "Zhou"
  second_string = "luobo"
  third_string = "Learn Python"
  fourth_string = first_string + second_string
  print(fourth_string)
  fifth_string = fourth_string + " " + third_string
  print(fifth_string)

  Output:
  Zhouluobo
  Zhouluobo Learn Python

  重复: 字符串可以用 * 符号重复。例如:
  print("Ha" * 3)

  Output:
  HaHaHa
  
  索引和切片: 我们已经确定字符串是从零开始索引的,我们可以使用其索引值访问字符串中的任何元素。我们还可以通过在两个索引值之间进行切片来获取字符串的子集。例如:
  main_string = "I learned English and Python with ZHouluobo. You can do it too!"
  # Index 0
  print(main_string[0])
  # Index 1
  print(main_string[1])
  # Check if Index 1 is whitespace
  print(main_string[1].isspace())
  # Slicing 1
  print(main_string[0:11])
  # Slicing 2:
  print(main_string[-18:])
  # Slicing and concatenation
  print(main_string[0:11] + ". " + main_string[-18:])

  Output:
  I
  True
  I learned English
  You can do it too!
  I learned English. You can do it too!


TAG: 软件开发 Python

 

评分:0

我来说两句

Open Toolbar