码迷,mamicode.com
首页 > 编程语言 > 详细

[python基础(二)]字符串方法

时间:2017-08-25 01:14:20      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:使用   函数   子串   this   rip   ima   http   ges   tran   

本文介绍了字符串两种重要的使用方式:字符串格式化和字符串方法。
一.字符串格式化

技术分享

技术分享

二.字符串方法

常用的字符串方法有:find,join,lower,replace,split,strip,translate。

具体的代码见下面

py文件
# -*- coding: utf-8 -*-


#字符串格式化

#1.简单转换
print ‘%s plus %s equals %s‘%(1,2,3)
from math import pi
print ‘Pi:%f...‘%pi

#2.字段宽度和精度
print ‘%10f‘ % pi # 3.141593 字段宽10
print ‘%10.2f‘ % pi # 3.14字段宽10,精度2
print ‘%.5s‘ %‘abcdefgh‘ #abcde
print ‘%.*s‘ %(5,‘abcdefgh‘) #*号

#3.符号、对齐和用0填充
print ‘%010f‘ %pi #003.141593 在宽度精度前放一个标志,可以是0,加,减号或空格,用于填充
print ‘%+10f‘ %pi # +3.141593 加号,用于标志符号
print ‘%-10f‘ %pi #减号,左对齐
print (‘%+10f‘ %pi)+‘\n‘+‘%+10f‘ %-pi # +3.141593 换行 -3.141593,左对齐

#字符串方法
#1.find:查找子串,返回最左端索引,没有返回-1
A=‘I am a student‘
print A.find(‘am‘) #2
print A.find(‘stu‘) #7
print A.find(‘su‘) #-1

#2.join:split的逆方法,用来连接序列中的元素
seq=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]
a=‘+‘
print a.join(seq) #1+2+3+4+5 注意顺序,不是seq.join(a)

#3.lower:返回字符串的小写字母版
print ‘AJDOEDD‘.lower()

#4.replace :返回某字符串的所以匹配项均被替换后的字符串
print ‘A and Hong are friends‘.replace(‘A‘,‘Ming‘)

#5.split join的逆方法,将字符串分割成序列
print ‘1+2+3+4+5‘.split(‘+‘) #[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]

#6.strip 返回去除两侧空格的字符串(可以去除无意加上的空格)
print ‘ A is B ‘.strip() #A is B

#7.translate 替换字符中的某些部分,只处理单个字符,可同时进行多个替换
from string import maketrans
table =maketrans(‘AB‘,‘CD‘) #maketrans函数接受两个参数:两个等长的字符串,效果如下
print ‘this is A and B‘.translate(table) #this is C and D


[python基础(二)]字符串方法

标签:使用   函数   子串   this   rip   ima   http   ges   tran   

原文地址:http://www.cnblogs.com/youngsea/p/7425933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!