字串常用操作

2021-07-04 15:26:28 字數 4648 閱讀 3048

#-*-coding:utf-8-*-

import string

1、判斷str/unicode字串物件

def

isastring

(anobj):

return isinstance(anobj,basestring) #basesting是str,unicode的父類

defisaint

(anobj):

''''''

return isinstance(anobj,int)

for i in [1,1.1,true,0,3e-1,4e2]:

if isaint(i):

print

" a int!"

else:

print

"not a int!"

print

"i=",i

help(basestring)

help(isinstance)

help(type)

print type('a')

print type("好的")

print type(1.2)

print type(1)

print type([1,2,3])

print type()

print type((1,23))

print type()

f = open("a.txt",'r')

print type(f)

f.close()

print isastring('hello,pyton')

print isastring(u'\8338')

print isastring(3990)

print isastring(chr(58))

2、字串左、中、右對齊

print

"|",'hello,python'.rjust(20,'+') #width引數表示長度,包括對齊的字串+間隔字元

print

'|','hello,python'.ljust(20,'*') #左對齊,不足寬度的字元以'*'填充

print

'|','hello,python1'.center(20,'-') #不加第二個引數預設新增空格

s = "hello,python"

print s.title()

print dir(str)

help(str.title)

help(s.rjust)

3、去除字串兩端空格

x = "    hello,python   "

print x.lstrip()+'here'

print x.strip()

print x.rstrip()

y = "here, hello,python, here"

print y.strip('hre') #去除字串y左右兩邊的'h'/'r'/'e'字元

4、字串合併

strs = ['hello',',','python']

print

'/'.join(strs) #join函式接受字串列表引數

largestring = ''

for s1 in strs:

largestring += s1

print

"largestring=",largestring

print

"source string =%s,%f" % ("hello,python ",1.0003)

help(str.join)

"""使用格式化字串合併字串是最優的選擇"""

name = 'zroad'

number = 100

print

"hello,%s;go and %d" %(name,number)

5、反轉字串的簡單實現方法:

chars = 'zroadyh'

revchars = chars[::-1]

print "revchars = %s" % revchars

words = "this is a very good boy !"

print "words.splite()=" , words.split()

print " ".join(words.split()[::-1])

6、檢查字串中是否包含某字元集合中的字元

def

containsany

(seq,aset):

""" 檢查序列seq中是否包含sset中的項

"""for c in seq:

if c in aset:

return

true

return

false

print containsany("abc","world,ello")

print containsany(['1','2','3','a','b','c'],['11','b'])

help(str.translate)

7、str.maketrans/str.translate的使用

"""

替換、刪除字串中的指定字元

"""table = string.maketrans('12','@*') #將字串中的字元'1','2'替換為'@','@'

print "adbd1kekk32#".translate(table,'ka') #param(table,deletechars)

8、過濾字串中不屬於指定集合的字元

"""

使用到閉包函式,需要關注

"""allchars = string.maketrans("", "") #定義translate翻譯表

print

"allchars=",allchars

defmakefilter

(keep):

""" 返回乙個函式,此函式接受keep引數,返回乙個字元拷貝,僅包含keep中的字串

"""delchars = allchars.translate(allchars,keep)

defthefilter

(s):

#閉包函式的定義

return s.translate(allchars,delchars)

return thefilter

if __name__ == "__main__":

filter1 = makefilter("obcd")

print

"the result=" , filter1("hello,python!aaa,bbb,ccc,ddd")

9、字串的大小寫控制

srcchar = "abc,hello,world"

print srcchar.upper()

print srcchar.lower()

print srcchar.capitalize() #abc,hello,world

print srcchar.title() #abc,hello,world

10、其他操作

import sys

#將字串轉換為序列

strlist = list("hello,python!")

print strlist

#遍歷字串中的任意一字元

for char in

"hello,python!":

#print char

#print char, #print不換行的處理

sys.stdout.write(char)

sys.stdout.flush()

print

'\n'

#輸出字串不換行的第二種處理

sys.stdout.write("hello,world!")

sys.stdout.flush()

#使用map函式遍歷字串中的每個字元

results = map(ord,"hello,python")

print results

#asc||/unicode單字串與碼值轉換

print ord('a') #asc||字串 『a』對應的碼值

print chr(97) #asc||碼97對應的字元

#str()與repr()的區別,str函式針對的是asc||碼

print ord(u'\u2020') #unicode字元\u2020對應的碼值

print repr(unichr(8224)) #將unicode碼值轉換為unicode字元

#將字串轉換為列表

file = "c:/workspace/test/python/hello.py"

ldir = file.split('/')

print

"ldir=", ldir #ldir= ['c:', 'workspace', 'test', 'python', 'hello.py']

字串常用操作。。。

include include include char itoa int value result char malloc sizeof char i 1 for j 0 jint i 65 char p itoa i printf s n p free p p null include incl...

字串常用操作

一 變換大小寫 string.tolowercase string.touppercase var big qwertyu big.tolowercase qwertyu var yh qwertyui yh.touppercase qwertyui 二 獲取字串長度 var yy 好好學習前端做個...

字串常用操作

strip將輸入資訊前後空格去除 username input username if username.strip liangml print welcome split name liangml,tom,jack name2 name.split 拆分以逗號分隔的字串得到乙個列表 print j...