python笔记5

目录

 1、字符串的基本操作

2、格式化字符串

1、占位符格式化字符串:

2、f-strings格式化字符串:

3、format()格式化字符串:

4、format详细格式控制:

3、字符串函数数据验证


1、字符串的基本操作

  1. 字符串连接:使用 + 运算符可以将两个字符串连接起来。
    str1 = "Hello"
    str2 = "World"
    result = str1 + " " + str2
    print(result)
    
  2. 字符串复制:使用 * 运算符可以将一个字符串复制多次。
    original = "abc"
    repeated = original * 3
    print(repeated)
    
  3. 字符串长度:使用 len() 函数可以获取字符串的长度。
    text = "Hello, World!"
    length = len(text)
    print(length)
    
  4. 字符串索引和切片:使用索引获取字符串中的单个字符,索引从0开始。
    text = "Python"
    first_char = text[0]
    print(first_char)
    

    使用切片获取子字符串。

    text = "Python"
    sub_str = text[1:4]  # 获取索引1到3的子字符串
    print(sub_str)
    
  5. 字符串查找:使用 find() 方法可以查找子字符串在主字符串中的位置。
    text = "Hello, World!"
    index = text.find("World")
    print(index)
    
  6. 字符串替换:使用 replace() 方法可以替换字符串中的子字符串。

    text = "Hello, World!"
    new_text = text.replace("World", "Universe")
    print(new_text)
    
  7. 字符串大小写转换:使用 lower() 和 upper() 方法可以将字符串转换为小写和大写。

    text = "Hello"
    lower_case = text.lower()
    upper_case = text.upper()
    
  8. 字符串去除空格:使用 strip() 方法可以去除字符串两端的空格。

    text = "   Some text with spaces   "
    trimmed_text = text.strip()
    

    也可以选择使用 lstrip() 方法(只去除左侧空格)或 rstrip() 方法(只去除右侧空格)来实现单侧空格的去除。例如:

    text = "   Hello, World!   "
    left_stripped_text = text.lstrip()  # 去除左侧空格
    right_stripped_text = text.rstrip()  # 去除右侧空格
    

    strip()也允许指定一个字符集合作为参数,用于去除字符串两端包含在该字符集合中的字符。以下是 strip(char) 方法的示例:

    text = "+++Hello, World!+++"
    stripped_text = text.strip('+')
    print(stripped_text)#输出Hello, World!
    

    lstrip(),rstrip()也一样

  9. 将一个字符串分割成多个子字符串:

    在 Python 中,split() 方法是用于将一个字符串分割成多个子字符串的方法。默认情况下,split() 方法使用空格作为分隔符,将字符串分割成一个字符串列表。也可以指定其他分隔符作为参数。

    以下是 split() 方法的基本用法:

    text = "Hello, World!"
    words = text.split()
    print(words)
    

    上述代码会输出:

    ['Hello,', 'World!']
    

    在这个例子中,默认的空格作为分隔符,将字符串 "Hello, World!" 分割成了两个子字符串 "Hello," 和 "World!"。

    还可以使用自定义的分隔符。例如:

    text = "apple,banana,orange"
    fruits = text.split(',')
    print(fruits)
    

    上述代码会输出:

    ['apple', 'banana', 'orange']
    

    在这个例子中,逗号 , 被指定为分隔符,将字符串 "apple,banana,orange" 分割成了一个包含三个元素的列表。

    需要注意的是,split() 方法返回一个包含分割后子字符串的列表。如果不提供分隔符,默认使用空格分割。如果字符串中有连续的分隔符,split() 方法会将它们视为一个分隔符,不会在结果列表中添加空字符串。

  10. 将一个字符串居中:

    center(width, char) 是字符串方法,用于将一个字符串居中,并在两侧填充指定字符,使其达到指定的宽度。

    以下是 center(width, char) 方法的示例:

    text = "Hello, World!"
    centered_text = text.center(20, '*')
    print(centered_text)
    

    上述代码输出:

    ***Hello, World!***
    

    在这个例子中,center(20, '*') 方法将字符串 text 居中,并使用星号 * 在两侧填充,使整个字符串的宽度为 20 个字符。

    如果指定的宽度小于原始字符串的长度,则返回原始字符串,因为无需填充。

    你可以根据需要选择不同的填充字符,或者不指定填充字符,默认使用空格进行填充。例如:

    text = "Hello, World!"
    centered_text_spaces = text.center(20)  # 默认使用空格填充
    print(centered_text_spaces)
    

2、格式化字符串

1、占位符格式化字符串:

在 Python 中,字符串格式化的占位符可以使用 % 运算符进行,这称为旧式字符串格式化。

以下是一个使用占位符 % 的字符串格式化示例:

name = "Charlie"
age = 28
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)

上述代码输出:

My name is Charlie and I am 28 years old.

在这个例子中,%s 表示字符串占位符,%d 表示整数占位符。% 运算符后的括号中的值会按顺序替换相应的占位符。

以下是一些常用的占位符:

  • %s: 字符串
  • %d: 十进制整数
  • %f: 浮点数

    你可以根据需要选择不同的占位符。如果要格式化多个值,需要将它们放在一个元组中,作为 % 运算符右侧的值。

    需要注意的是,旧式字符串格式化在 Python 3.6 及以上版本中已不推荐使用,而推荐使用 format() 方法或 f-strings。这两种方法更灵活、可读性更好,并且有更好的性能。

    2、f-strings格式化字符串:

    f-strings 是在 Python 3.6 及以上版本引入的一种字符串格式化方法。它使用在字符串前加上字母 "f" 并包含花括号 {} 来表示表达式的方式。这使得在字符串中嵌入变量和表达式更加直观和简洁。

    以下是一些使用 f-strings 的示例:

    1. 基本用法:

      name = "Alice"
      age = 30
      formatted_string = f"My name is {name} and I am {age} years old."
      print(formatted_string)
      

      输出:

      My name is Alice and I am 30 years old.
      
    2. 表达式嵌入:

      x = 5
      y = 10
      result = f"The sum of {x} and {y} is {x + y}."
      print(result)
      

      输出:

      The sum of 5 and 10 is 15.
      
    3. 数字格式化:

      pi_value = 3.14159
      formatted_pi = f"The value of pi is {pi_value:.2f}"
      print(formatted_pi)
      

      输出:

      The value of pi is 3.14
      
    4. 使用变量和表达式:

      a = 3
      b = 4
      result = f"The square of the sum of {a} and {b} is {(a + b)**2}"
      print(result)
      

      输出:

      The square of the sum of 3 and 4 is 49.
      

      f-strings 的优势在于它们简洁、易读,而且性能通常比其他字符串格式化方法更好。它是一种推荐使用的字符串格式化方式,特别是在需要动态生成字符串时。

    3、format()格式化字符串:

    在 Python 中,使用 format() 方法进行字符串格式化是一种更现代和灵活的方式。这个方法允许你使用大括号 {} 作为占位符,并通过 format() 方法中的参数进行替换。

    以下是一个使用 format() 方法的字符串格式化示例:

    name = "David"
    age = 35
    formatted_string = "My name is {} and I am {} years old.".format(name, age)
    print(formatted_string)
    

    上述代码输出:

    My name is David and I am 35 years old.
    

    在这个例子中,{} 占位符会按照它们在字符串中的顺序被 format() 方法中的参数替换。

    还可以使用位置参数或关键字参数来明确指定占位符的替换值:

    formatted_string = "My name is {0} and I am {1} years old.".format(name, age)
    # 或者
    formatted_string = "My name is {name} and I am {age} years old.".format(name=name, age=age)
    

    这两种方式都可以达到相同的效果。format() 方法也支持更复杂的格式化,例如指定字段宽度、精度等。详细如下文。

    4、format详细格式控制:

    1. 字段宽度和对齐:
      text = "Hello"
      formatted_text = "{:>10}".format(text)
      print(formatted_text)
      

      输出:

       Hello
      

      在这个例子中,{:>10} 表示使用字段宽度为 10,并且右对齐。可以使用 < 进行左对齐,^ 进行居中对齐。

    2. 精度控制:

      pi_value = 3.14159
      formatted_pi = "{:.2f}".format(pi_value)
      print(formatted_pi)
      

      输出:

      3.14
      

      在这个例子中,{:.2f} 表示格式化为带有两位小数的浮点数。

    3. 符号、千位分隔符和正负号:

      number = -1234567
      formatted_number = "{:+,}".format(number)
      print(formatted_number)
      

      输出:

      -1,234,567
      
      在这个例子中,{:+,}表示包括正负号并使用千位分隔符。{:-,}和 {:+,}都是在格式化数字时使用的格式说明符,它们分别表示不显示正号和显示正号,并且使用千位分隔符。
    4. 二进制、八进制和十六进制:
      value = 42
      formatted_binary = "Binary: {:b}".format(value)
      formatted_octal = "Octal: {:o}".format(value)
      formatted_hex = "Hexadecimal: {:x}".format(value)
      print(formatted_binary)
      print(formatted_octal)
      print(formatted_hex)
      

      输出:

      Binary: 101010
      Octal: 52
      Hexadecimal: 2a
      

    3、字符串函数数据验证

    1. isdigit(): 用于检查字符串是否只包含数字字符。
      numeric_string = '12345'
      if numeric_string.isdigit():
          print("Valid numeric string.")
      else:
          print("Invalid numeric string.")
      
    2. isalpha(): 用于检查字符串是否只包含字母字符。
      alpha_string = 'abc'
      if alpha_string.isalpha():
          print("Valid alphabetic string.")
      else:
          print("Invalid alphabetic string.")
      
    3. isalnum(): 用于检查字符串是否只包含字母和数字字符。
      alphanumeric_string = 'abc123'
      if alphanumeric_string.isalnum():
          print("Valid alphanumeric string.")
      else:
          print("Invalid alphanumeric string.")
      
    4. isspace(): 用于检查字符串是否只包含空白字符(空格、制表符、换行符等)。
      space_string = '   '
      if space_string.isspace():
          print("Valid space string.")
      else:
          print("Invalid space string.")
      
    5. 大小写相关函数:                                                                                                                    isupper(): 检查字符串中的所有字母是否都是大写。                                                             islower(): 检查字符串中的所有字母是否都是小写。

      uppercase_string = 'HELLO'
      lowercase_string = 'hello'
      if uppercase_string.isupper():
          print("Valid uppercase string.")
      else:
          print("Invalid uppercase string.")
      if lowercase_string.islower():
          print("Valid lowercase string.")
      else:
          print("Invalid lowercase string.")
      
    6. startswith() 和 endswith(): 用于检查字符串是否以特定的前缀或后缀开始或结束。

      text = 'Hello, World!'
      if text.startswith('Hello'):
          print("String starts with 'Hello'.")
      if text.endswith('World!'):
          print("String ends with 'World!'.")
      
    7. isnumeric() 和 isdecimal():                                                                                        isnumeric()检查字符串是否只包含数字字符,包括数字字符和其他一些特殊字符(如罗马数字)。                                                                                                                          isdecimal()检查字符串是否只包含十进制数字字符。

      numeric_string = '12345'
      roman_numeral = 'XII'
      if numeric_string.isnumeric():
          print("Valid numeric string.")
      if roman_numeral.isnumeric():
          print("Valid numeric string with special characters.")
      

    4、join()

    join()是一个字符串方法,用于将字符串序列(例如列表或元组)中的元素连接起来,形成一个新的字符串。在执行 方法时,你可以指定一个字符串作为分隔符,该分隔符将用于在连接的字符串之间插入。join()

    语法:

    string.join(iterable)
    
    • string:用于连接字符串的分隔符。
    • iterable:一个可迭代的对象,包含需要连接的字符串序列。

      示例:

      # 使用空格作为分隔符连接字符串列表中的元素
      my_list = ['Hello', 'World', 'Python']
      result = ' '.join(my_list)
      print(result)  # Output: Hello World Python
      # 使用逗号作为分隔符连接元组中的元素
      my_tuple = ('apple', 'banana', 'cherry')
      result = ', '.join(my_tuple)
      print(result)  # Output: apple, banana, cherry
      

      在上面的示例中,join() 方法将字符串列表中的元素连接起来,并使用空格作为分隔符。类似地,它也可以用于连接元组中的元素,并在它们之间插入逗号。结果是一个新的字符串,包含了所有元素并用指定的分隔符分隔。