字符串基本操作汇总

'''
python编程视频第二套27集 配套书籍 Python开发技术详解
字符串操作
'''
#格式化字符串
str1="version"
num=1.0
#因为字符串类型为string,所有用s参数占位符来表示对其格式化
format="%s"%str1
print format
#>>> version
format = "%s %d" %(str1,num)
print format
#>>> version 1

#带精度的格式化
print "浮点型数字:%f"%1.25
print "浮点型数字:%.1f"%1.25
print "浮点型数字:%.2f"%1.254
# 浮点型数字:1.250000
# 浮点型数字:1.2
# 浮点型数字:1.25

#使用字典格式化字符串
#第一个参数version对应着字典中的第一个键值对的值version,第二参数格式化num对应着第二个键值对version的值2
print "%(version)s:%(num).1f"%{"version":"version","num":2}
#>>> version:2.0

#字符串对齐
word ="version3.0"
print word.center(20)
print word.center(20,"*")
print word.ljust(0)
print word.rjust(20)
print "%30s"%word
#从输出结果中可知上面表示的意思。
#>>> version:2.0
#>>> version3.0
#>>> *****version3.0*****
#>>> version3.0
#>>> version3.0
#>>> version3.0




1 #转义符
path ="hello world "
print path
print len(path)

#r可使转义符失效
path = r"hello world "
print path
print len(path)
输出结果如图:

从中可知: :表示制表符,相当于tab键; 相当于换行符,会换一行;r:使转义符失效。

2 #strip()去掉转义符
word=" hello world "
print "直接输出:",word
print "strip()后输出:",word.strip()
print "Istrip()后输出:",word.lstrip() #去除左侧的第一个转义符
print "rstrip()后输出:",word.rstrip() #去除右侧的第一个转义符
从结果中就可知道表达的意思。


3 #字符串连接
'''
使用"+"连接字符串
'''
str2="world "
str1="hello "
str3="hello "
str4="china "
result = str1+str2+str3+str4
print result
#>>> hello world hello china
#使用join()连接字符串
strs=["hello ","sorld ",'hello ',"china "]
result="".join(strs)
print result
#>>> hello sorld hello china
#使用reduce()连接字符串
import operator
strs=["hello ","world ","hello ","china "]
result=reduce(operator.add,strs,"") #导入operater模块下的加法操作
print result
#>>> hello world hello china
 


4 #使用索引截取字符串
word ="world"
print word[4]
#>>> d
#使用split()获取子串
sentence = 'Bob said:1,2,3,4'
print "使用空格取子串:",sentence.split()
print "使用逗号取子串:",sentence.split(",")
print "使用两个逗号取子串:",sentence.split(",",2)
#>>> 使用空格取子串: ['Bob', 'said:1,2,3,4']
#>>> 使用逗号取子串: ['Bob said:1', '2', '3', '4']
#>>> 使用两个逗号取子串: ['Bob said:1', '2', '3,4']

# 字符串连接后分配新的空间
#使用join连接字符串可以节省空间,有下面可知。
str1="a"
print id(str1)
print id(str1+"b")
#>>> 35070800
#>>> 35347224

#特殊切片截取子串
str1 = "hello world"
print word[0:3]
print str1[::2] #以步长为2从0开始取子串
print str1[1::2] #从1开始取子串,并且以步长为2的开始取子串。
#>>> wor
#>>> hlowrd
#>>> el ol

#字符串的比较
str1 = 1
str2="1"
if str1 ==str2:
print "same"
else:
print "difference"

#比较字符串的开始和结束处
word = "hello world"
print "hello"==word[0:5]
print word.startswith("hello") #匹配开始的hello五个字符
print word.endswith("ld",6) #匹配结果为ld的子串,从6开始
print word.endswith('ld',6,10) #匹配结果为ld的子串,查找范围为6到10
print word.endswith("ld",6,len(word))

输出结果为:

 

6 #字符串的反转
#使用list的reverse()方法
def reverse(s):
li = list(s)
print type(li)
li.reverse()
s="".join(li)
return s
print reverse("hello")
#>>> <type 'list'>
#>>> olleh

#循环输出反转的字符串
def reverse1(s):
out=""
li = list(s)
for i in range(len(li)):
out +="".join(li[i-1])
return out
print reverse1("hello")

#>>> olleh

#特殊切片反转字符串
def reverse2(s):
return s[::-1]
print reverse2("hello")
#>>> olleh

 #字符串的查找与替换操作
sentence = "this is an apple"
print sentence.find("a") #第一次出先a的位置
print sentence.rfind("a") #从右边开始查找a的位置。
#>>> 8
#>>> 11


#字符串的替换
centence1="hello,world,hello china"
print centence1.replace("hello","hi")
print centence1.replace("hello","hi",1)
print centence1.replace("abc","hi")
#>>> hi,world,hi china
#>>> hi,world,hello china
#>>> hello,world,hello china

#字符串与日期的转换
import time
import datetime
#时间字符串转换
print time.strftime("%Y-%m-%d %X",time.localtime())
#字符串到时间的转换
t = time.strptime("2008-08-09","%Y-%m-%d")
y,m,d=t[0:3]
print datetime.datetime(y,m,d)
#>>> 2017-09-05 18:50:46
#>>> 2008-08-09 00:00:00

原文地址:https://www.cnblogs.com/papapython/p/7481385.html