String as a common data types, in daily life we are faced with a variety of string-handling issues, then this requires us to have some common string handling functions, here I will take you one by one to find out there which string functions and use
First, the string functions finishing
capitalize() | The first character of the string to uppercase |
casefold() | All the characters in the entire string to lowercase |
center(width) | String center, and padded with spaces to the width of the new string length |
count(sub[, start[, end]]) | Returns the number of sub occurring inside the string, start and end parameters indicates a range, optional. |
encode(encoding='utf-8', errors='strict') | To encoding specified encoding format for encoding strings. |
endswith(sub[, start[, end]]) | Check whether the string sub substring end, a return True, otherwise False. parameter indicates the start and end range, optional. |
expandtabs([tabsize=8]) | The tab character string (\ t) are converted to spaces, if not specified, the default is the number of spaces tabsize = 8. |
find(sub[, start[, end]]) | Detecting whether the sub contained in the string, if the index value is returned, otherwise -1, start and end parameters indicates a range, optional. |
index(sub[, start[, end]]) | Like find methods, but not if the sub string will produce an exception. |
isalnum () | If there is at least one character string and all the characters are letters or numbers returns True, otherwise False. |
Islf () | If there is at least one character string and all the characters are the letters return True, otherwise False. |
isdecimal () | If the string contains only decimal digits returns True, otherwise False. |
isdigit() | If the string contains only digit returns True, otherwise False. |
islower() | These characters If the string contains at least one of alphanumeric characters, and all lowercase, True is returned, otherwise it returns False. |
isnumeric() | If the string contains only numeric characters, it returns True, otherwise False. |
isspace() | If the string contains only spaces, returns True, otherwise False. |
istitl A () | If the string is the title (all the words are in uppercase began rest of the letters are in lower case), then returns True, otherwise False. |
isupper() | If the string contains at least one case sensitive characters, and these characters are uppercase, True is returned, otherwise it returns False. |
join(sub) | String as a separator interposed between all of the characters in the sub. |
light (width) | Returns a string left-aligned and padded with spaces to the width of the length of the new string. |
lower() | Convert a string to all uppercase characters to lowercase. |
lstrip() | Remove all of the strings of spaces left |
partition(sub) | Found sub substring, the string into a 3-tuple (pre_sub, sub, fol_sub), if the string is not included in the sub returns ( 'original string', '', '') |
replace(old, new[, count]) | Replace the old sub-string to string new substring, if the count is specified, alternatively no more than count times. |
rfind(sub[, start[, end]]) | Similar to the find () method, but is beginning to find the right. |
rindex(sub[, start[, end]]) | Similar to the index () method, but starting from the right. |
rjust(width) | Returns a string right justified and padded with spaces to the width of the length of the new string. |
rpartition (sub) | Similar to the partition () method, but is beginning to find the right. |
rstrip() | Remove spaces at the end of the string. |
split(sep=None, maxsplit=-1) | The list is not the default parameters spliced substring after the separator to space string sections, if maxsplit parameters set, only the partition maxsplit substrings, returns slice. |
split lines (([notch ends])) | Whether to remove the line breaks in the output, the default is False, it does not contain line breaks; If True, the reserved line breaks. . |
startswith(prefix[, start[, end]]) | Check whether the string starts with prefix, it returns True, otherwise False. parameters may specify start and end range check, optional. |
strip([chars]) | Delete all strings front and back spaces, chars parameter can be customized character deleted, optional. |
swapcase() | Flip case string. |
title() | Returns the title (all the words are in uppercase start, the rest of the letters are lowercase) string. |
translate(table) | The rules table (may be made str.maketrans ( 'a', customized 'b')) of the character string conversion. |
upper() | Conversion string all lowercase characters to uppercase. |
zfill(width) | Returns a string of length to width, the original string is right-justified with zero-padded front. |
Second, the commonly used string functions and use
1, detects the character string contains
find (): detecting whether a string contains a specific character, and if the index contains a specific starting position is returned; otherwise -1
# find()函数
str = 'hello Python3'
# 查找'Py'是否在字符串中
print( str.find('Py') )
#输出:6
# 查找'word'是否在字符串中
print( str.find('word') )
#输出:-1
index (): detects whether the string contains the specified character, if you include the index value of the start of the return; otherwise prompt ValueError: substring not found error
# index()函数
str1 = 'hello Python3'
#'wo'在字符串中
print( str1.index('Py') )
#输出结果:6
#'word'不在字符串中,程序报错ValueError终止运行
print( str1.index('word') )
#输出结果: ValueError: substring not found
2, the number of statistics appear count () (with the same number of statistical database)
## count()函数
str2 = 'hello world'
# 统计str2中全部字母l的个数
print( str2.count('l') )
#输出结果:3
# 统计str2中从第5+1个字母到最后一个字母中,字母l的个数
print( str2.count('l', 5, len(str2)) )
#输出结果:1
3, replace () replacement character value
Syntax: str1.replace (str2, count) will replace str1 str1 to str2, if the specified count, no more than count times;
str3 = 'hello world hello world'
str5 = 'world'
str6 = 'waltsmith'
# 将str3中所有的str5替换为str6
print( str3.replace(str5, str6) )
# 在str3中只将前1个str5替换为str6
print( str3.replace(str5, str6, 1) )
4, split () according to the divided all splittable delimiter
基本语法格式:str.split('分界符', maxSplit)
maxSplit默认值为-1
#split()函数
str7 = 'I Love Python!'
# 以空格分割字符串,分界符默认为空格
print(str7.split(' ', 3))
# 以字母o作为分界符,指定最大分割为2,将返回最大分割+1个元素的列表
print(str7.split('o', 1))
#输出:
#['I', 'Love', 'Python!']
#['I L', 've Python!']
5、字符串转化大小写
capitalize()将字符串的首字母大写,其余字母全部小写;语法:str.capitalize()
#capitalize()函数
str8 = 'i Love Python!'
# 字符串的首字母大写,其余字母全部小写
print(str8.capitalize())
## 输出:I love python!
title()将字符串中的所有单词的首字母大写,其余字母全部小写;语法:str.title()
#title()函数
str9 = "i love python"
print(str9.title())
#输出:I Love Python
#字符中包含标点符号
str10 = "I lOVE pYthon"
print(str10.title())
#输出:I Love Python
lower()将字符串的所有字母转换为小写;语法:str.lower()
#lower()函数
str11 = "I LOVE PYTHON"
print(str11.lower())
#输出:i love python
upper()将字符串的所有字母转换为大写;语法:str.upper()
#upper()函数
str12 = "i love python"
print(str12.upper())
#输出:I LOVE PYTHON
startswith()检查字符串str是否 以字符串str1开头,若是则返回True;否则返回False;
#startswith()函数
str15 = "Hello Python"
print(str15.startswith("Hello"))
print(str15.startswith("My"))
#分别输出:True Flase
endswith()检查字符串str是否 以字符串str1结尾,若是则返回True;否则返回False;
#endswith()函数
str16 = "Hello Walt Smith"
print(str16.endswith("Smith"))
print(str16.endswith("Hello"))
#分别输出:True Flase
6、使用空格填充至指定长度
ljust()将字符串左对齐,并使用空格填充至指定长度len;语法:str.ljust(len)
#ljust()函数
str17 = "Hello"
print(str17.rjust(18))
print("str17的原长度为%d"% (len(str17)))
print("str17处理后的长度为%d" % (len(str17.ljust(20))))
#输出结果:
#----------Hello
#str17的原长度为5
#str17处理后的长度为20
rjust()将字符串右对齐,并使用空格填充至指定长度len;语法:str.rjust(len)
#rjust()函数
str18 = "Hello"
print(str18.rjust(18))
print("str18的原长度为%d" % (len(str18)))
print("str18处理后的长度为%d" % len(str18))
#输出:
# --------------Hello
# str18的原长度为5
# str18处理后的长度为18
center()将字符串居中,并使用空格填充至指定长度len;语法:str.center(len)
#center()函数
str19 = "Hello"
print(str19.center(20))
print("st19的原长度为%d" % (len(str19)))
print("str19处理后的长度为%d" % (len(str19.center(20))))
#输出结果:
#-------Hello-----
#st12的原长度为5
#str12处理后的长度为20
7、去掉字符串中空格值
lstrip()去掉字符串左边的空白字符;语法:str.lstrip()
#lstrip()函数
str20 = " Hello Python"
print(str20.lstrip())
#输出:Hello Python
rstrip()去掉字符串右边的空白字符;语法:str.rstrip()
#rstrip()函数
str21 = " Hello Walt Smith "
print(str21.rstrip())
#输出: -----Hello Walt Smith
strip()去掉字符串左右两边的空白字符;语法:str.strip()
#strip()函数
str22 = " Hello Python "
print(str22.strip())
#输出:Hello Walt Smith
8、partition()在str中若str1不存在,则将str作为第一部分,后面两个元素为空;返回元组;
#partition()函数
str25 = "Are you believe in yourself?"
# "yourself"在字符串中
print(str25.partition("yourself"))
# "you"在字符串中有两个
print(str25.partition("you"))
# "walt"不在字符串中
print(str25.partition("walt"))
#输出:
#('Are you believe in ', 'yourself', '?')
#('Are ', 'you', ' believe in yourself?')
#('Are you believe in yourself?', '', '')
9、join()将iterable中每两个相邻元素中间插入字符串str,返回形成的新的字符串;语法:str.join(iterable)
#join()函数
str26 = "walt"
print(str26.join("ABC"))
iterable = ['YOU', 'THEY', 'WE']
print(str26.join(iterable))
## 输出:
## AwaltBwaltC
## YOUwaltTHEYwaltWE
10、判断字符串的类型是否是指定的
isspace()如果字符串str中只包含空格,则返回True;否则返回False;语法:str.isspace()
#isspace()函数
str27 = " t "
print(str27.isspace())
#输出: False
isdigit()如果字符串str中只包含数字,则返回True;否则返回False;语法:str.isdigit()
#isdigit()函数
str28 = "12356"
print(str28.isdigit())
#输出: True
isalpha()如果字符串str中只包含字母,则返回True;否则返回False;
#isalpha()函数
str29 = "MrYu"
print(str29.isalpha())
#输出:True