Python中的string模块的学习

简介:

学习资料:http://docs.python.org/library/string.html#string.Formatter

感觉学习任何东西,官方的东西总是最好的,呵呵。个人总结(代码为主,相信有python基础的都能看懂):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>>  import  string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.octdigits
'01234567'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.whitespace
'\t\n\x0b\x0c\r

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
>>>  '{0}, {1}, {2}' . format ( 'a' 'b' 'c' )
'a, b, c'
>>>  '{}, {}, {}' . format ( 'a' 'b' 'c' )   # 2.7+ only
'a, b, c'
>>>  '{2}, {1}, {0}' . format ( 'a' 'b' 'c' )
'c, b, a'
>>>  '{2}, {1}, {0}' . format ( * 'abc' )       # unpacking argument sequence
'c, b, a'
>>>  '{0}{1}{0}' . format ( 'abra' 'cad' )    # arguments' indices can be repeated
'abracadabra'
 
>>>  'Coordinates: {latitude}, {longitude}' . format (latitude = '37.24N' , longitude = '-115.81W' )
'Coordinates: 37.24N, -115.81W'
>>> coord  =  { 'latitude' '37.24N' 'longitude' '-115.81W' }
>>>  'Coordinates: {latitude}, {longitude}' . format ( * * coord)
'Coordinates: 37.24N, -115.81W'
 
>>> c  =  3 - 5j
>>> ( 'The complex number {0} is formed from the real part {0.real} '
...   'and the imaginary part {0.imag}.' ). format (c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>>  class  Point( object ):
...      def  __init__( self , x, y):
...          self .x,  self .y  =  x, y
...      def  __str__( self ):
...          return  'Point({self.x}, {self.y})' . format ( self = self )
...
>>>  str (Point( 4 2 ))
'Point( 4 2 )
 
>>> coord  =  ( 3 5 )
>>>  'X: {0[0]};  Y: {0[1]}' . format (coord)
'X: 3;  Y: 5'
 
>>>  "repr() shows quotes: {!r}; str() doesn't: {!s}" . format ('test1 ', ' test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
 
>>>  '{:<30}' . format ( 'left aligned' )
'left aligned                  '
>>>  '{:>30}' . format ( 'right aligned' )
'                 right aligned'
>>>  '{:^30}' . format ( 'centered' )
'           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'
 
>>>  '{:,}' . format ( 1234567890 )
'1,234,567,890'
 
>>> points  =  19.5
>>> total  =  22
>>>  'Correct answers: {:.2%}.' . format (points / total)
'Correct answers: 88.64%'
 
>>>  import  datetime
>>> d  =  datetime.datetime( 2010 7 4 12 15 58 )
>>>  '{:%Y-%m-%d %H:%M:%S}' . format (d)
'2010-07-04 12:15:58'
 
>>>  for  align, text  in  zip ( '<^>' , [ 'left' 'center' 'right' ]):
...      '{0:{fill}{align}16}' . format (text, fill = align, align = align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets  =  [ 192 168 0 1 ]
>>>  '{:02X}{:02X}{:02X}{:02X}' . format ( * octets)
'C0A80001'
>>>  int (_,  16 )
3232235521
>>>
>>> width  =  5
>>>  for  num  in  range ( 5 , 12 ):
...      for  base  in  'dXob' :
...          print  '{0:{width}{base}}' . format (num, base = base, width = width),
...      print
...
     5      5      5    101
     6      6      6    110
     7      7      7    111
     8      8     10   1000
     9      9     11   1001
    10      A     12   1010
    11      B     13   1011
 
>>>  from  string  import  Template
>>> s  =  Template( '$who likes $what' )
>>> s.substitute(who = 'tim' , what = 'kung pao' )
'tim likes kung pao'
>>> d  =  dict (who = 'tim' )
>>> Template( 'Give $who $100' ).substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder  in  string: line  1 , col  10
>>> Template( '$who likes $what' ).substitute(d)
Traceback (most recent call last):
[...]
KeyError:  'what'
>>> Template( '$who likes $what' ).safe_substitute(d)
'tim likes $what'

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
string.capitalize(word) 返回一个副本,首字母大写
>>> string.capitalize( "hello" )
'Hello'
>>> string.capitalize( "hello world" )
'Hello world'
 
>>> string.split( "asdadada asdada" )
[ 'asdadada' 'asdada' ]
 
>>> string.strip( "              adsd         " )
'adsd'
>>> string.rstrip( "              adsd         " )
'              adsd'
>>> string.lstrip( "              adsd         " )
'adsd         '
 
string.swapcase(s) 小写变大写,大写变小写
>>> string.swapcase( "Helloo" )
'hELLOO'
 
>>> string.ljust( "ww" , 20 )
'ww                  '
>>> string.rjust( 'ww' , 20 )
'                  ww'
>>> string.center( 'ww' , 20 )
'         ww         '
string.zfill(s, width)
Pad a numeric string on the left with zero digits until the given width  is  reached. Strings starting with a sign are handled correctly.
>>> string.zfill( 'ww' , 20 )
'000000000000000000ww'

  

 


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/11/25/2263722.html,如需转载请自行联系原作者
相关文章
|
2月前
|
数据库 Python
Python学习的自我理解和想法(18)
这是我在学习Python第18天的总结,内容基于B站千锋教育课程,主要涉及面向对象编程的核心概念。包括:`self`关键字的作用、魔术方法的特点与使用(如构造函数`__init__`和析构函数`__del__`)、类属性与对象属性的区别及修改方式。通过学习,我初步理解了如何利用这些机制实现更灵活的程序设计,但深知目前对Python的理解仍较浅显,欢迎指正交流!
|
1月前
|
安全 数据安全/隐私保护 Python
Python学习的自我理解和想法(27)
本文记录了学习Python第27天的内容,主要介绍了使用Python操作PPTX和PDF的技巧。其中包括通过`python-pptx`库创建PPTX文件的详细步骤,如创建幻灯片对象、选择母版布局、编辑标题与副标题、添加文本框和图片,以及保存文件。此外,还讲解了如何利用`PyPDF2`库为PDF文件加密,涵盖安装库、定义函数、读取文件、设置密码及保存加密文件的过程。文章总结了Python在处理文档时的强大功能,并表达了对读者应用这些技能的期待。
|
2月前
|
数据采集 机器学习/深度学习 自然语言处理
Python学习的自我理解和想法(16)
这是我在B站千锋教育课程中学Python的第16天总结,主要学习了`datetime`和`time`模块的常用功能,包括创建日期、时间,获取当前时间及延迟操作等。同时简要介绍了多个方向的补充库,如网络爬虫、数据分析、机器学习等,并讲解了自定义模块的编写与调用方法。因开学时间有限,内容精简,希望对大家有所帮助!如有不足,欢迎指正。
|
1月前
|
存储 搜索推荐 算法
Python学习的自我理解和想法(28)
本文记录了学习Python第28天的内容——冒泡排序。通过B站千锋教育课程学习,非原创代码。文章详细介绍了冒泡排序的起源、概念、工作原理及多种Python实现方式(普通版、进阶版1和进阶版2)。同时分析了其时间复杂度(最坏、最好、平均情况)与空间复杂度,并探讨了实际应用场景(如小规模数据排序、教学示例)及局限性(如效率低下、不适用于高实时性场景)。最后总结了冒泡排序的意义及其对初学者的重要性。
|
2月前
|
Python
Python学习的自我理解和想法(19)
这是一篇关于Python面向对象学习的总结,基于B站千锋教育课程内容编写。主要涵盖三大特性:封装、继承与多态。详细讲解了继承(包括构造函数继承、多继承)及类方法与静态方法的定义、调用及区别。尽管开学后时间有限,但作者仍对所学内容进行了系统梳理,并分享了自己的理解,欢迎指正交流。
|
1月前
|
Python
Python学习的自我理解和想法(26)
这是一篇关于使用Python操作Word文档的学习总结,基于B站千锋教育课程内容编写。主要介绍了通过`python-docx`库在Word中插入列表(有序与无序)、表格,以及读取docx文件的方法。详细展示了代码示例与结果,涵盖创建文档对象、添加数据、设置样式、保存文件等步骤。虽为开学后时间有限下的简要记录,但仍清晰梳理了核心知识点,有助于初学者掌握自动化办公技巧。不足之处欢迎指正!
|
2月前
|
数据采集 数据挖掘 Python
Python学习的自我理解和想法(22)
本文记录了作者学习Python第22天的内容——正则表达式,基于B站千锋教育课程。文章简要介绍了正则表达式的概念、特点及使用场景(如爬虫、数据清洗等),并通过示例解析了`re.search()`、`re.match()`、拆分、替换和匹配中文等基本语法。正则表达式是文本处理的重要工具,尽管入门较难,但功能强大。作者表示后续会深入讲解其应用,并强调学好正则对爬虫学习的帮助。因时间有限,内容为入门概述,不足之处敬请谅解。
|
2月前
|
设计模式 数据库 Python
Python学习的自我理解和想法(20)
这是我在B站千锋教育课程中学习Python第20天的总结,主要涉及面向对象编程的核心概念。内容包括:私有属性与私有方法的定义、语法及调用方式;多态的含义与实现,强调父类引用指向子类对象的特点;单例设计模式的定义、应用场景及实现步骤。通过学习,我掌握了如何在类中保护数据(私有化)、实现灵活的方法重写(多态)以及确保单一实例(单例模式)。由于开学时间有限,内容简明扼要,如有不足之处,欢迎指正!
|
2月前
|
索引 Python
Python学习的自我理解和想法(24)
本文记录了学习Python操作Excel的第24天内容,基于B站千锋教育课程。主要介绍openpyxl插件的使用,包括安装、读取与写入Excel文件、插入图表等操作。具体内容涵盖加载工作簿、获取单元格数据、创建和保存工作表,以及通过图表展示数据。因开学时间有限,文章简要概述了各步骤代码实现,适合初学者参考学习。如有不足之处,欢迎指正!
|
1月前
|
Python
Python学习的自我理解和想法(25)
这是一篇关于Python操作Word文档(docx)的教程总结,基于B站千锋教育课程学习(非原创代码)。主要内容包括:1) docx库插件安装;2) 创建与编辑Word文档,如添加标题、段落、设置字体样式及保存;3) 向新或现有Word文档插入图片。通过简单示例展示了如何高效使用python-docx库完成文档操作。因开学时间有限,内容精简,后续将更新列表和表格相关内容。欢迎指正交流!

热门文章

最新文章

推荐镜像

更多