Python中String模块示例详解

2022-12-27

string模块主要包含关于字符串的处理函数,这篇文章主要介绍了Python中String模块示例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

目录
  • Python中String模块详解
  • 一、 字符串常量
  • 二、 类
    • 1、 格式化
      • 1.1 介绍
      • 1.2 简单应用
      • 1.3 格式化输出
    • 2、 模板化
    • 三、 函数

      Python中String模块详解

      一、 字符串常量

      String库中的内置的所有常量:

      源码中的概括:

      whitespace -- a string containing all ASCII whitespace
      ascii_lowercase -- a string containing all ASCII lowercase letters
      ascii_uppercase -- a string containing all ASCII uppercase letters
      ascii_letters -- a string containing all ASCII letters
      digits -- a string containing all ASCII decimal digits
      hexdigits -- a string containing all ASCII hexadecimal digits
      octdigits -- a string containing all ASCII octal digits
      punctuation -- a string containing all ASCII punctuation characters
      printable -- a string containing all ASCII characters considered printable

      示例:

      # -*- coding: utf-8 -*-
      """
      Created on Sun Dec 18 18:58:35 2022
      
      @author: Steve Anthony
      """
      import string
      print(string.whitespace)  # 包含所有的空格
      print(string.ascii_lowercase)  # 包含所有的小写字母
      print(string.ascii_uppercase)  # 包含所有的大写字母
      print(string.ascii_letters)  # 包含ASCII中的所有字母
      print(string.digits)  # 包含所有的数字字符串
      print(string.hexdigits)  # 包含所有的十六进制字符字符串
      print(string.octdigits)  # 包含所有的八进制字符字符串
      print(string.punctuation)  # 包含所有的标点符号字符串
      print(string.printable)  # 包含所有可打印的ASCII字符字符串

      二、 类

      1、 格式化

      1.1 介绍

      String模块中,有一个Formatter类,其可以对字符串进行格式化。

      该类中有一个format()方法,和str.format()方法使用方式类似,同时该类的主要作用就是使用format()方法,对字符串进行格式化输出。

      1.2 简单应用

      print('{0}, {1}, {2}'.format('a', 'b', 'c'))
      print('{}, {}, {}'.format('a', 'b', 'c'))  # 3.1+ only
      print('{2}, {1}, {0}'.format('a', 'b', 'c'))  
      print('Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W'))
      

      同时,也可以结合元组或者字典的解包来使用。

      1.3 格式化输出

      >>> '{:<30}'.format('left aligned')  # 向右对齐,保留30个字符,如果字符不够使用空格填充
      'left aligned                  '
      >>> '{:>30}'.format('right aligned')  # 向左对齐,保留30个字符,如果字符不够使用空格填充
      '                 right aligned'
      >>> '{:^30}'.format('centered')  # 居中对齐,保留30个字符,如果字符不够使用空格填充
      '           centered           '
      >>> '{:*^30}'.format('centered')  # use '*' as a fill char
      '***********centered***********'
      
      
      >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
      '+3.140000; -3.140000'
      >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
      ' 3.140000; -3.140000'
      >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
      '3.140000; -3.140000'
      
      >>> # format also supports binary numbers
      >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
      'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
      >>> # with 0x, 0o, or 0b as prefix:
      >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
      'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
      >>> 'Correct answers: {:.2%}'.format(19/22)  # 保留两位小数
      'Correct answers: 86.36%'

      还可以用于对时间等特殊字符串的格式化

      import datetime
      d = datetime.datetime(2010, 7, 4, 12, 15, 58)
      print('{:%Y-%m-%d %H:%M:%S}'.format(d))

      2、 模板化

      模板字符串提供了更简单的字符串替换。因为在该上下文中,更简单的语法和功能使其比 Python 中的其他内置字符串格式设施更容易翻译。

      模板字符串支持基于$的替换,使用以下规则:

      • 使用$$进行转义,其代表$本身
      • $Identity 命名一个替换占位符,该占位符与映射关键字“ Identity”匹配。默认情况下,“标识符”仅限于以下划线或 ASCII 字母开头的任何不区分大小写的 ASCII 字母数字字符串(包括下划线)。$字符之后的第一个非标识符字符终止此占位符规范
      • ${identifier} 等价于 $identifier

      使用示例:

      # -*- coding: utf-8 -*-
      """
      Created on Sun Dec 18 18:58:35 2022
      
      @author: Steve Anthony
      """
      from string import Template
      
      s = Template('$who的年龄为:${age}')
      print(s.safe_substitute({"who": "李华", "age": 13}))  # safe_*这个函数如果没有给字符串里面的所有变量赋值不会报错
      print(s.safe_substitute(**{"who": "李华"}))
      print(s.substitute(**{"who": "李华", "age": 13}))  # 但是这个函数,必须要给字符串里面所有定义的变量都赋值,否则会报错
      print(s.substitute({"who": "李华"}))

      三、 函数

      对于String的常用方法,可以去Python基础语法里面学习

      同时,有一个比较特殊的函数capwords(s, sep=" "),可以学习学习

      作用,根据分隔符,将字符串分成几块,并且将每一块字符串的第一个字母转换为大写字母(如果不是字符则不改变),其余字母转换为小写字母,最后使用分隔符拼接回去。

      使用示例:

      # -*- coding: utf-8 -*-
      """
      Created on Sun Dec 18 18:58:35 2022
      
      @author: Steve Anthony
      """
      import string
      
      a = string.capwords("*hello python! my nAmE iS")
      print(a)

      到此这篇关于Python中String模块的文章就介绍到这了,更多相关Python中String模块内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

      《Python中String模块示例详解.doc》

      下载本文的Word格式文档,以方便收藏与打印。