码迷,mamicode.com
首页 > 其他好文 > 详细

字符串操作

时间:2018-01-20 11:07:39      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:基本   切割   beginning   string   利用   class   end   word   ace   

字符串:

定义:  字符串是一个有序的字符的集合,用于存储和表示基本的文本信息,‘ ‘或‘‘ ‘‘或‘‘‘ ‘‘‘中间包含的内容称之为字符串。

 特性:1. 有序 2. 不可变

 

技术分享图片

 

操作:

必须熟记的有:

1. .isdigit()

2. .replace ()

3. .find()

4. .count()

5. .strip()

6. center

7. split

8. join

9. format

 

s= ‘Hello World! ‘

s.swapcase()     # 大写变小写,小写变大写:  变成 ‘hELLO wORLD! ‘  , s.swapcase( ) 不是修改了原值,而是生成了一个新的值。

s.capitalize()    #只把首字母大写

s.casefold()    # 把所有字母变成小写

 

**  s.center( width, fillchar(str))   #  Return s centered in a string of length width. Padding is done using the specified fill character (default is a space).       

如: s.center(15,‘-‘) 为  ‘--Hello World--‘  

  

** s.count (substring, start(int), end(int) )       # -> int       Return the number of non-overlapping occurrences of substring ‘substring‘ in string s[start:end].  Optional arguments start and end are interpreted as in slice notation.

如: s.count( ‘o‘) 为 2   就是字符串s里面有2个‘o‘

        s.count( ‘o‘, 0,5 )  为  1    就是字符串s从索引 0 到 5 中只有一个‘o‘。

        s.center(20,‘-‘).count(‘--‘)    为 4

 

s.endswith( suffix, start(int), end(int) )    # -> 布尔    判断字符串s是否以字符串suffix结尾。    # Return True if s ends with the specified suffix, False otherwise.     With optional start, test s beginning at that position.With optional end, stop comparing S at that position(类似于切片的“顾头不顾尾”). suffix can also be a tuple of strings to try.        

 

s2 = ‘a\tb‘    #   \t就是Tab键 

s2.expandtabs(tabsize)    # 扩展Tab键, tabsize如果不写,默认为8或者4,  

如: s2.expandtabs(20)   为 ‘a                   b‘  

 

** 查找索引值1:  s.find( sub, start, end)   # -> int     查找某个子字符串所在的索引值。    # Return the lowest index in s where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation.     Return -1 on failure.

如: s.find(‘o‘) 为  4,    

        s.find(‘lo‘) 为 3,

        s.find(‘o‘,6,)  为  7   # 即使截取查找, 找到的也是该子字符串在整个字符串s中的索引值

查找索引值2:  s.index( sub, start, end)     #用法跟s.find相同, 区别: find找不到会返回-1; index找不到则会报错。 

 

** 格式化输出: format

第一种用法:

 s3 = ‘I am {0}, and I am {1} years old‘
 s4= s3.format(‘Neo‘,18)
 print(s4)

输出结果为 :  I am Neo, and I am 18 years old   

第二种用法:

s3 = ‘I am {name}, and I am {age} years old‘
s4= s3.format(name=‘Neo‘, age = 18)
print(s4)

输出结果为:  I am Neo, and I am 18 years old 

  

s.isalnum()  #-> 布尔   # 用于判断字符串s中是不是只有数字和字母,如果出现特殊字符则返回False。     官方解释 : Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.

判断字符串中是不是只有字母: s.isalpha( )   # -> 布尔   # 官方解释: Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.

 

判断字符串中是不是只有整数:  s.isdecimal()     (没搞懂,decimal不是小数吗 ??、。。。)

** 判断字符串中是不是只有整数:     s.isdigit()      #.。。。  跟 s.isdecimal啥区别 ???

判断字符串中是不是只有整数:      s.isnumeric()


 .isidentifier()   #判断是不是辨识符 

 

s.islower()  # 判断字符串里面的字母是否都是小写 

s.isupper()  #判断里面的字母是不是都是大写

s.istitle()  # 判断各个单词的首字母是不是都大写

 

** 把列表变成字符串: ‘‘.join( )

如: 

names = [ ‘alex‘,‘jack‘,‘neo‘]

‘‘.join(names)  输出结果为  ‘alexjackneo‘ 

‘,‘.join(names)  输出结果为  ‘alex,jack,neo‘

‘-‘.join(names) 输出结果为  ‘alex-jack-neo‘       #想用什么隔开转化的names的元素, 引号里面用输入什么。

 

s.ljust(width, fillchar)   #  -> str      # Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).   如果不够就填充fillchar。

如: s= ‘Hello world‘   

s.ljust(50,‘-‘)  为   ‘Hello world---------------------------------------‘   

s.ljust(4) 为 ‘  Hello world‘

 

s.lower()   #把字符串s里面的都变成小写     ps: 和 .casefold()啥区别? 

s.upper()   #把字符串s里面的都变成大写

 

** s.strip()  # 把Tab键、换行和空格都去掉

如: s = ‘\n hello world        ‘     #\n 就是换行

s.strip() 为    ‘hello world‘

s.lstrip()    #只去掉左边,不去掉右边

s.rstrip()     #只去掉右边,不去掉左边

 

制作对应表、并翻译(类似于密码映射关系):

s= ‘hello alex‘

#先设立对应关系
str_in = ‘abcdfe‘
str_out = ‘&@#$(!‘     #两个字符串里面的个数必须一样   

#得到映射关系表格
table = str.maketrans(str_in,str_out)      #利用maketrans()把str_in里面的元素一一对应到str_out中

#利用table中的映射关系去翻译s

s1= s.translate(table) 
print(s1) 

输出结果为:  ‘h!llo &l!x‘    # 没有设定对应关系的元素不翻译。

  

** 替换字符串中的元素: s.replace(old, new, count) # 官方解释: Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced(只有前count个被替换).

 

s.rfind( ) #从右开始找字符串s中的某个元素(括号内输入要找的元素),输出其索引值(注:索引值都是从左向右计算的)。 具体用法同 s.find( ) , 可切割去rfind。

s.rindex() # 用法类似于s.rfind(), 区别也是在于找不到会不会报错。

 

** 把字符串变成列表用 : s.split(sep, maxsplit )     #把字符串分开,存放于一个列表中    解释:  Return a list of the words in S, using sep as the delimiter string.  If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. 

s = ‘hello world‘

s.split() 为 [‘hello‘, ‘world‘]    #默认以空格分。

s.split(‘l‘) 为 [‘he‘, ‘‘, ‘o wor‘, ‘d‘]      # 用谁分, 谁就没了

s.split( ‘l‘, 1) 为  [‘he‘, ‘lo world‘]      #maxsplit为1, 最多只分一次,从左开始。

s.rsplit()  #从右边开始分

s.rsplit(‘l‘ , 1)  为   [‘hello wor‘, ‘d‘]    #从右边开始分,只分一次

s.splitlines()   # 换行来分

如:

a = ‘a\nb\ncd\nneo‘  

a.splitlines() 为  [‘a‘, ‘b‘, ‘cd‘, ‘neo‘]

 

判断字符串是否以某元素开始: a.startswith( prefix, start, end)   #官方解释: Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position.With optional end, stop comparing S at that position.prefix can also be a tuple of strings to try.

可对比s.endswith() 去理解。

 

把首字母都变成大写: s.title()

 

字符串操作

标签:基本   切割   beginning   string   利用   class   end   word   ace   

原文地址:https://www.cnblogs.com/neozheng/p/8315435.html

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