字符串操作

字符串:

定义:  字符串是一个有序的字符的集合,用于存储和表示基本的文本信息,' ''' ''''' '''中间包含的内容称之为字符串。
特性:1. 有序 2. 不可变 

两个字符串拼接:

直接利用“+”, 如: string1+string2 

操作:

常用的有:

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.islower()  # 判断字符串里面的字母是否都是小写 
s.isupper()  #判断里面的字母是不是都是大写
s.istitle()  # 判断各个单词的首字母是不是都大写
s.lower()   #把字符串s里面的都变成小写     ps: 和 .casefold()啥区别? 
s.upper()   #把字符串s里面的都变成大写
s.title()  # 把首字母都变成大写:

居中:center()

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--'  

统计个数:count()

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

判断字符串是否以什么开关:startswith()

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() 去理解。 

判断字符串是否以什么结尾:endswith()

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.        

扩展:expandtabs()

s2 = 'a\tb'    #   \t就是Tab键 
s2.expandtabs(tabsize)    # 扩展Tab键, tabsize如果不写,默认为8或者4,  
如: s2.expandtabs(20)   为 'a                   b'  

查找索引值: find() 和 index()

# 查找索引值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()

# 格式化输出: 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()    # 判断字符串中是不是只有整数
# **  isdigit():
s.isdigit()  # 判断字符串中是不是只有整数
s.isnumeric()  # 判断字符串中是不是只有整数

判断是不是辨识符 

s.isidentifier()

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

** 把列表变成字符串: 
''.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'

去掉空格、Tab键和换行: strip()

# ** strip()
s.strip()  # 把Tab键、换行和空格都去掉; 官方解释: Return a copy of the string s with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead(这句没看懂).

#如: 
s = '\n hello world        '     #\n 就是换行
s.strip()   # 为 'hello world'
s.lstrip()    #只去掉左边,不去掉右边
s.rstrip()     #只去掉右边,不去掉左边

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

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'    # 没有设定对应关系的元素不翻译。

字符串替换: replace()

# ** 替换字符串中的元素: 
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个被替换)

字符串分隔: split()

# ** 把字符串变成列表用 : 
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']

另外。split也有如下用法:

a = 'neo,22,male,tianjin'

name,age,gender,city = a.split(',')

print(name)
print(age)
print(gender)
print(city)

# 输出结果:
# neo
# 22
# male
# tianjin
Code your future.
原文地址:https://www.cnblogs.com/neozheng/p/8315435.html