`

Python基础教程之第3章 使用字符串

阅读更多
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
#3.1基本字符串操作
>>> website = 'http://www.python.org'
>>> website[-3:]='com'

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    website[-3:]='com'
TypeError: 'str' object does not support item assignment
#3.2 字符串格式化:精简版
>>> format = "Hello, %s. %s is enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world. Hot is enough for ya?
>>> format = "Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142
#模板字符串
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
>>> s = Template("Make $$ selling $x!")
>>> s.substitute(x='slurm')
'Make $ selling slurm!'
>>> s = Template('A $thing must never $action.')
>>> d={}
>>> d['thing']='gentleman'
>>> d['action']='show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
>>> #saft_substitute不会因缺少值或不正确使用$字符而出错.
>>> '%s plus %s equlas %s' % (1,1,2)
'1 plus 1 equlas 2'
>>> '%s plus %s equlas %s' % 1,1,2

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    '%s plus %s equlas %s' % 1,1,2
TypeError: not enough arguments for format string
>>> '%s plus %s equlas %s' % 1,1,2 # Lacks parentheses!

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    '%s plus %s equlas %s' % 1,1,2 # Lacks parentheses!
TypeError: not enough arguments for format string
#3.3 字符串格式化:完整版
#3.3.1简单转换
>>> 'Price of eggs: $%d' % 42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs: %x' % 42
'Hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'Pi: %f...' % pi
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' % pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
'Using str: 42'
>>> 'Using repr: %r' % 42L
'Using repr: 42L'
#3.3.2字段宽度和精度
>>> '%10f' % pi
'  3.141593'
>>> '%10.2f' % pi
'      3.14'
>>> '%.2f' % pi
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
>>> '%.*s' % (5, 'Guido van Rossum')
'Guido'
#3.3.3符号, 对齐和0填充
>>> '%010.2f' % pi
'0000003.14'
>>> 010
8
>>> '%-10.2f' % pi
'3.14      '
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)F
SyntaxError: invalid syntax
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)
   10
  -10
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)F
SyntaxError: invalid syntax
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)
   10
  -10
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
  +10
  -10
  
#代码清单3-1 字符串格式化示例
#3.4字符串方法
#string模块还包括一些不能作为字符串方式使用的常量和函数
>>> import string
>>> string.digits
'0123456789'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#3.4.1 find
>>> 'With a moo-moo here. and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title.find('Monty')
0
>>> title.find('Python')
6
>>> titie.find('Flying')

Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    titie.find('Flying')
NameError: name 'titie' is not defined
>>> title.find('Flying')
15
>>> title.find('Zirquss')
-1
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16)
-1
#3.4.2 join
>>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)

Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq = ['1','2','3','4','5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:' + '\\'.join(dirs)
C:\usr\bin\env
#3.4.3 lower
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
>>> if 'Gumby' in ['gumby','smith','jones']: print 'Found it!'

>>> name='Gumby'
>>> names=['gumby','smith','jones']
>>> if name.lower() in names: print 'Found it!'

Found it!
#标题转换
>>> "that's all folks".title()
"That'S All Folks"
>>> import string
>>> string.capwords("that's all, folks")
"That's All, Folks"
#3.4.4 replace
>>> 'This is a test'.replace('is','eez')
'Theez eez a test'
#3.4.5 split
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']
#3.4.6 strip 相当于Java 中的 String.trim()
>>> '     internal whitespace is kept    '.strip()
'internal whitespace is kept'
>>> names = ['gumby','smith','jones']
>>> name = 'gumby'
>>> if name in names: print 'Found it!'

Found it!
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'
#3.4.7 translate
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
>>> table = maketrans('cs','kz')
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
>>> 'this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'
#非英语字符串问题
table = maketrans('X','x')
word = 'Xxx'
print word.translate(table).lower()
print u'Xxx'.lower()

#小结
#本章介绍了字符串的两种非常重要的使用方式
#字符串格式化: 求模操作符(%)可以用来将其他值转换为包含转换标志的字符串,例如%s. 它还能用来对值进行不同方式的格式化,
#包括左右对齐, 设定字段宽度以及精度,增加符号(正负号)或者左填充数字0等.
#字符串方法 有些非常有用,比如split和join,有些则用得很少,比如istitle或capitalize.

#本章的新函数
#string.capwords(s[, sep])	使用split函数分割字符串s(以sep为分隔符),使用capitalize函数将分割得到的各单词首字母大写,并且使用join函数以sep为分隔符
#将各单词连接起来
#string.maketrans(from,to)	创建用于转换的转换表
#接下来学什么 列表, 字符串和字典是Python中最重要的3种数据类型.


代码清单3-1 字符串格式化示例
#e3-1
#使用给定的宽度打印格式化后的价格列表

width = input('Plese enter width: ')

price_width = 10
item_width = width - price_width;

#减号(-1)用来左对齐数值
header_format = '%-*s%*s'
format = '%-*s%*.2f'

print '=' * width

print header_format % (item_width, 'Item', price_width, 'Price')

print '-' * width

print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantaloupes', price_width, 1.92)
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)

print '=' * width

#python e3-1.py
#Plese enter width: 35
#===================================
#Item                          Price
#-----------------------------------
#Apples                         0.40
#Pears                          0.50
#Cantaloupes                    1.92
#Dried Apricots (16 oz.)        8.00
#Prunes (4 lbs.)               12.00
#===================================
分享到:
评论

相关推荐

    python基础教程 第三版 中文 高清 pdf

    目录 第1 章 快速上手:基础知识 1.1 交互式解释器 1.2 算法是什么 1.3 数和表达式 ...1.9.1 从命令提示符运行 Python 脚本 ...1.10 字符串 ...1.10.1 单引号字符串以及对引号转义 ...第3 章 使用字符串

    Python基础教程-03第三章使用字符串.pdf

    在第三章“使用字符串”中,我们探讨了字符串的一些基本操作、格式化以及特殊方法。以下是对这些概念的详细解释: 1. **基本字符串操作**: - **索引**:字符串中的每个字符都可以通过索引来访问,如`str[0]`获取...

    python第3章答案-【Python基础教程】第3章字符串.pdf

    在Python编程语言中,字符串是数据类型之一,用于存储文本信息。在本章中,我们将深入探讨Python字符串的特性和操作。 首先,我们要明白一个重要特性:**字符串是不可变的**。这意味着一旦创建了一个字符串,就不能...

    Python基础教程(第三版).pdf

    《Python基础教程(第三版)》是一本专为初学者设计的Python编程教材,全面覆盖了Python语言的基础知识,旨在帮助读者快速掌握Python编程技能。本教程以清晰易懂的语言和丰富的实例,引领读者深入理解Python的核心...

    Python基础教程 第三版

    **Python基础教程第三版概述** Python是一种高级编程语言,以其简洁、易读的语法和强大的功能而闻名。作为初学者入门编程或者专业人士增强技能的工具,Python基础教程第三版是学习这一语言的理想资源。该高清版教程...

    python教程答案第三章-Python基础教程(第三章).pdf

    以上就是Python基础教程第三章的主要内容,涵盖了字符串格式化、模板字符串、字符串方法等重要概念,这些都是Python编程中处理文本数据的基本技能。理解并掌握这些知识点,将有助于进一步学习和应用Python。

    python基础教程第二版

    《Python基础教程第二版》是针对初学者的一本经典教材,尤其适合那些对Python 2.0版本感兴趣的读者。本书全面、深入地介绍了Python编程语言的基础概念和语法,旨在帮助读者掌握这一强大而灵活的编程工具。以下是根据...

    python 基础教程第三版

    《Python基础教程(第3版)》是一本深入浅出的Python编程指南,适用于初学者和有一定经验的程序员。本书全面覆盖了Python语言的核心概念、语法结构以及实用技巧,旨在帮助读者快速掌握Python编程的基本技能。 在...

    python基础教程txt免费-Python基础教程(第2版).pdf

    第3章专注于字符串的使用,包括基本操作、字符串格式化,以及字符串方法,如查找、连接、大小写转换、替换、分割等。这有助于提升字符串处理的效率和灵活性。 第4章介绍了字典,这是一种基于键值对的数据结构,非常...

    python基础教程源代码-python基础教程第三版源代码.pdf

    《Python基础教程》第三版源代码是一份详细的学习资源,涵盖了Python编程的多个核心概念和实践技巧。这个源代码集合包括了从基础语法到高级特性的各种示例,旨在帮助初学者逐步掌握Python编程。 在Python的基础部分...

    python基础教程至60课基础

    Python 基础教程知识点总结 本资源摘要信息涵盖 Python 基础教程的 60 课内容,涵盖 Python 基础知识点的所有方面。...* 字符串格式化的扩展使用(Python 第 16 课) + 介绍字符串格式化的扩展用法和应用场景

    Python基础教程(第2版.修订版)

    第3章 使用字符串 第4章 字典:当索引不好用时 第5章 条件、循环和其他语句 第6章 抽象 第7章 更加抽象 第8章 异常 第9章 魔法方法、属性和迭代器 第10章 充电时刻 第11章 文件和素材 第12章 图形用户界面 ...

    完整版 零基础学Python课件05 第5章 字符串及表达式.ppt

    在Python中,字符串可以使用单引号、双引号或三引号来表示。字符串可以进行各种操作,如字符串连接、字符串分割、字符串检索、字符串格式化等。本文将详细介绍Python中字符串的各种操作和应用。 字符串常用操作 1....

    Python基础入门教程 由浅入深讲解清晰 第1章 基础知识 (共44页).ppt

    Python基础入门教程 由浅入深讲解清晰 第3章 选择与循环 (共44页).ppt Python基础入门教程 由浅入深讲解清晰 第4章 字符串与正则表达式 (共55页).ppt Python基础入门教程 由浅入深讲解清晰 第5章 函数的设计和...

    python基础教程第二版+源代码

    "Python基础教程第二版"是学习Python语言的经典教材,由专家编写,旨在为初学者提供全面而深入的Python知识。这本书包含了Python的基础概念、语法结构、数据类型、控制结构、函数、模块和包、面向对象编程以及错误...

    python基础教程的第三版中的源码

    在"Python基础教程的第三版"中,作者详细介绍了Python的基本概念和语法,为初学者提供了全面的学习路径。这个压缩包包含了该教程各章节的源码,使读者能够通过实践加深对每个概念的理解。 首先,我们可以从“第一章...

    Python基础教程(第2版·修订版)2014

    《Python基础教程(第2版·修订版)2014》是一本针对初学者的Python编程指南,它深入浅出地介绍了Python语言的核心概念和语法。这本书在2014年进行了修订,以适应Python语言的发展和变化,相较于2010年的版本,它...

    python基础教程 第三版 PDF文档+源码(高清 + 目录)珍藏版

    《Python基础教程》第三版是Python编程初学者的宝贵资源,由知名...无论你是自学还是在课堂上学习,这个珍藏版的《Python基础教程》第三版都是一个值得拥有的资源,它将引导你步入Python编程的世界,开启你的编程之旅。

    python中的real函数-RealPython基础教程:Python字符串用法详解.pdf

    字符串处理是编程中的基础,因为几乎每个应用程序都需要对文本进行操作。Python提供了丰富的功能来处理字符串,包括运算符、函数和类方法。 1. **字符串运算符**: - `+` 运算符用于字符串连接,它将两个或多个...

Global site tag (gtag.js) - Google Analytics