您的位置:首页 > 编程语言 > Python开发

Python基础教程代码与注释P46 3.3 字符串格式化:完整版 3.4 字符串方法

2018-01-15 18:56 856 查看
# -*- coding: cp936 -*-
#P46 3.3 字符串格式化:完整版
#元组中的每一个元素单独格式化,每个值需要一个对应的转换说明符
print '%s plus %s equals %s' % (1, 1, 2)
#print '%s plus %s equals %s' % 1, 1, 2 #Lacks parentheses缺少括号

#3.3.1 简单转换
print 'Price of eggs: $%d' % 42             # %d 十进制
print 'Hexadecimal price of eggs: %x' % 42  # %x 十六进制(x小写 X大写)
from math import pi
print 'Pi: %f...' % pi                      # %f 十进制浮点数
print 'Very inexact estimate of pi:%i' % pi # %i 十进制 %s
#str函数:把值转换为合理形式的字符串
print 'Using str: %s' % 42L                 # %s 字符串(使用str转换任意Python对象)
#repr函数:创建一个字符串,以合法的Python表达式形式来表示值
print 'Using repr: %r' % 42L                # %r 字符串(使用repr转换任意Python对象)

#3.3.2 字段宽度和精度
print '%10f' % pi                   #字段宽10
print '%10.2f' % pi                 #字段宽10,精度2
print '%.2f' % pi                   #精度2
print '%.5s' % 'Guido van Rossum'   #取前5个
print '%.15s' % 'Guido van Rossum'  #取前15个
print '%.*s' % (5, 'Guido van Rossum')  #使用 * 作为字段宽度或者精度,数值会从元组参数中读出。

#3.3.3 符号、对齐和用0填充
print '%010.2f' % pi                #字段宽10,精度2,右对齐,不足10位用0填充。
print 010
print '%-10.2f' % pi                #字段宽10,精度2,- 左对齐,输出后右侧多出额外空格。
print ('% 5d' % 10) + '\n' + ('% 5d' % -10) # % 5d之间的空白 意味着在正数前加上空格。对齐正负数时使用。
print ('%+5d' % 10) + '\n' + ('%+5d' % -10) # % 5d之间的 +   意味着不管正数不是负数都标出符号。

#codelist3-1 字符串格式化示例
print '#使用给定的宽度打印格式化后的价格列表'
width = input('Please enter width: ')   #输入宽度(列数)

price_width = 10                        #'Price'占的列数
item_width = width - price_width        #'Item'占的列数

header_format = '%-*s%*s'               #格式化列表头部
format        = '%-*s%*.2f'             #格式化列表内容

print '=' * width                       #打印输入的width个=号
#打印列表头部
print header_format % (item_width, 'Item', price_width, 'Price')

print '-' * width                       #打印输入的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 1bs.)', price_width, 12)

print '=' * width                       #打印输入的width个=号

raw_input("Press <enter>")

# -*- coding: cp936 -*-
#P49 3.4 字符串方法
#3.4.1 find     查找子串,返回子串所在位置的最左端索引。
print 'With a moo-moo here, and a moo-moo there'.find('moo')
title = "Monty Python's Flying Circus"
print title.find('Monty')
print title.find('Python')
print title.find('Flying')
print title.find('Zirquss') #没找到返回-1

#这段代码就用图片了,代码在博客中显示不对...

#接收可选的起始点和结束点参数
print subject.find('$$$', 1)#只提供起始点
print subject.find('ch', 0, 16)#提供起始点和结束点
print subject.find('!!!')
print subject.find('!!!', 0, 16) #提供起始点和结束点

#3.4.2 join     split方法的逆方法,用来连接序列中的元素。
seq = [1, 2, 3, 4, 5]
sep = '+'
#print sep.join(seq) #连接数字列表报错,必须是字符串
seq = ['1', '2', '3', '4', '5']
print sep.join(seq) #连接字符串列表
dirs = '','usr', 'bin', 'env'
print '/'.join(dirs)
print 'C:' + '\\'.join(dirs) + '\n'

#3.4.3 lower    返回字符串的小写字母版。
print 'Trondheim Hammer Dance'.lower()
if 'Gumby' in['gumby','smith', 'jones']:print 'Found it!' + '\n'
#name.lower()在存储和搜索时把所有名字都转换为小写。
name = 'Gumby'
names = ['gumby','smith', 'jones']
if name.lower() in names: print 'Found it!'
#title方法,将字符串转换为标题——所有单词首字母大写
print "that's all folks".title()
#string模块的capwords函数
import string
print string.capwords("that's all, folks") + '\n'

#3.4.4 replace  返回某字符串的所有匹配项均被替换之后得到字符串。
print 'This is a test'.replace('is', 'eez') + '\n'

#3.4.5 split    join方法的逆方法,将字符串分割成序列。
print '1+2+3+4+5'.split('+')
print '/user/bin/env'.split('/')

#3.4.6 strip    返回去除两侧(不包括内部)空格的字符串
print '
9626
internal whitespace is kept        '.strip()
name = 'Gumby '#假设名字后面加上了空格
names = ['gumby','smith', 'jones']
if name.lower().strip() in names: print 'Found it!'
print '***SPAM*for*everyone!!!***'.strip('*!') + '\n'#指定需要去除的字符(仅两侧)

#3.4.7 translate    类似replace,但只处理单个字符。
#使用translate转换之前,先完成一张转换表。使用string模块的maketrans函数
from string import maketrans
table = maketrans('cs', 'kz')
print len(table)
print table[97:123]
print maketrans('', '')[97:123]
#将转换表作为translate方法的参数
print 'this is an incredible test'.translate(table)
print 'this is an incredible test'.translate(table, ' ') #删除所有空格

raw_input("Press <enter>")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: