python字符串常用的方法解析
这是本人在学习python过程中总结的一些关于字符串的常用的方法.
文中引用了python3.5版本内置的帮助文档,大致进行翻译,并添加了几个小实验.
isalnum
S.isalnum() -> bool #字符串里所有的字符都是字母或者数字时返回True,否则返回False
Return True if all characters in S are alphanumeric and there is
at least one character in S, False otherwise.
>>> str1="hello world"
>>> str2="hello555 world"
>>> str3="66666"
>>> str4="hello"
>>> str1.isalnum()
False
>>> str2.isalnum()
False
>>> str3.isalnum()
True
>>> str4.isalnum()
True
isalpha
S.isalpha() -> bool #字符串里所有的字符都是字母时返回True,否则返回False
Return True if all characters in S are alphabetic and there is
at least one character in S, False otherwise.
>>> str1="hello world"
>>> str2="hello555 world"
>>> str3="66666"
>>> str4="hello"
>>> str1.isalpha()
False
>>> str2.isalpha()
False
>>> str3.isalpha()
False
>>> str4.isalpha()
True
isdigit#####
S.isdigit() -> bool #字符串里所有字符都是数字则返回True,否则返回False
Return True if all characters in S are digits and there is at
least one character in S, False otherwise.
>>> str1="hello world"
>>> str2="hello555 world"
>>> str3="66666"
>>> str1.isdigit()
False
>>> str2.isdigit()
False
>>> str3.isdigit()
True
islower
S.islower() -> bool #字符串所有的字符都是小写字母时返回True,否则返回False
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
>>> str1="hello world"
>>> str2="66666"
>>> str3="HELLO WORLD"
>>> str1.islower()
True
>>> str2.islower()
False
>>> str3.islower()
False
istitle
S.istitle() -> bool #每个单词的首字母大写时返回True,否则返回False
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
>>> str1="hello world"
>>> str2="Hello World"
>>> str3="HELLO WORLD"
>>> str1.istitle()
False
>>> str2.istitle()
True
>>> str3.istitle()
False
isupper
S.isupper() -> bool #字符串里所有的字符都是大写字母时返回True,否则返回False
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
>>> str1="hello world"
>>> str2="66666"
>>> str3="HELLO WORLD"
>>> str1.isupper()
False
>>> str2.isupper()
False
>>> str3.isupper()
True
lower
S.lower() -> str #把字符串里所有的字符都转换为小写字母
Return a copy of the string S converted to lowercase.
>>> str3="HELLO WORLD"
>>> str3.lower()
'hello world'
upper
S.upper() -> str #把字符串里所有的字符都转换为大写字母
Return a copy of S converted to uppercase.
>>> str1="hello world"
>>> str1.upper()
'HELLO WORLD'
strip
S.strip([chars]) -> str #去除字符串里的空格
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.
>>> str1=" hello world "
>>> str2="hello world "
>>> str1.strip()
'hello world'
>>> str2.strip()
'hello world'
isspace
S.isspace() -> bool #字符串里所有的字符都为空格时返回True,否则返回False
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
>>> str1=" "
>>> str2="hello world"
>>> str1.isspace()
True
>>> str2.isspace()
False
replace
S.replace(old, new[, count]) -> str #把字符串里指定的字符替换成新的字符
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.
>>> str1="hello world"
>>> str1.replace("l","L")
'heLLo worLd'
>>> str2="abababababababab"
>>> str2.replace("a","c")
'cbcbcbcbcbcbcbcb'
index
S.index(sub[, start[, end]]) -> int #返回字符串里的子字符串的索引
Like S.find() but raise ValueError when the substring is not found.
>>> str1="abcdefg"
>>> str1.index("a")
0
>>> str1.index("f")
5
find
S.find(sub[, start[, end]]) -> int #在字符串里查找指定的子串,未找到时返回-1,找到则返回子串在字符串中的索引值
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.
>>> str1="abcdefg"
>>> str2="ababab"
>>> str1.find("bc")
1
>>> str2.find("b")
1
>>> str1.find("f")
5
split
S.split(sep=None, maxsplit=-1) -> list of strings #根据指定的符号分隔字符串
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 and empty strings are
removed from the result.
>>> str1="/etc/sysconfig/selinux"
>>> str1.split("/")
['', 'etc', 'sysconfig', 'selinux']
>>> str2="abc|mnt|xyz"
>>> str2.split("|")
['abc', 'mnt', 'xyz']
startswith
S.startswith(prefix[, start[, end]]) -> bool #字符串以指定的字符开头时返回True,否则返回False
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.
>>> str1="hello world"
>>> str2="abcdefg"
>>> str1.startswith("hello")
True
>>> str2.startswith("abc")
True
endswith
S.endswith(suffix[, start[, end]]) -> bool #字符串以指定的字符结尾时返回True,否则返回False
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.
>>> str1="hello world"
>>> str2="abcdefg"
>>> str1.startswith("hello")
True
>>> str2.startswith("abc")
True
>>> str1.endswith("ld")
True
>>> str2.endswith("fg")
True
lstrip
S.lstrip([chars]) -> str #仅去除字符串左边的空格
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
>>> str1=" hello world "
>>> str2=" hello world"
>>> str3="hello world "
>>> str1.lstrip()
'hello world '
>>> str2.lstrip()
'hello world'
>>> str3.lstrip()
'hello world '
rstrip
S.rstrip([chars]) -> str #仅去除字符串右边的空格
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
>>> str1=" hello world "
>>> str2=" hello world"
>>> str3="hello world "
>>> str1.rstrip()
' hello world'
>>> str2.rstrip()
' hello world'
>>> str3.rstrip()
'hello world'
rfind
S.rfind(sub[, start[, end]]) -> int #返回子串在字符串中的索引值
Return the highest 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.
>>> str1="hello world"
>>> str2="abcdefg"
>>> str1.rfind("world")
6
>>> str1.rfind("r")
8
>>> str2.rfind("e")
4
>>> str2.rfind("g")
6
format
S.format(*args, **kwargs) -> str #格式化输出指定的字符串
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
>>> print("{name}======>{age}".format(name="tom",age=22))
tom=========>22
>>> print("{name}======>{age}".format(age=22,name="tom"))
tom=========>22
swapcase
S.swapcase() -> str #把字符串中的小写字母变成大写,大写字母变成小写
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
>>> str1="HELLO world"
>>> str1.swapcase()
'hello WORLD'
>>> str2="hello WORLD"
>>> str2.swapcase()
'HELLO world'
title
S.title() -> str #把字符串中的每个单词变成大写字母开头
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
>>> str1="hello world"
>>> str1.title()
'Hello World'
>>> str2="this is a test string"
>>> str2.title()
'This Is A Test String'
join
S.join(iterable) -> str #把字符串混合插入到一个迭代器中
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>> str1="abcd"
>>> str2="xyz"
>>> str1.join(str2)
'xabcdyabcdz'
capitalize
S.capitalize() -> str #把字符串中的首字母变成大写
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
>>> str1="hello world"
>>> str1.capitalize()
'Hello world'
>>> str1="linux"
>>> str1.capitalize()
'Linux'
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)
>>> str1="hello world"
>>> str1.center(30,"#")
'############linux#############'
>>> str2="linux"
>>> str2.center(16,"*")
'*****linux******'
count
S.count(sub[, start[, end]]) -> int #判断子串在字符串中出现的次数
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
>>> str1="hello world"
>>> str1.count("l")
3
>>> str2="aaaaaaaaaaaa"
>>> str2.count("a")
12
ljust
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).
>>> str1="hello world"
>>> str1.ljust(20,"@")
'hello world@@@@@@@@@'
>>> str2="linux"
>>> str2.ljust(18,"&")
'linux&&&&&&&&&&&&&'
rjust
S.rjust(width[, fillchar]) -> str #扩充字符串到指定长度,不足由第二个参数从左边填充,默认为空格
Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
>>> str1="hello world"
>>> str2="linux"
>>> str1.rjust(30,"#")
'###################hello world'
>>> str2.rjust(14,"$")
'$$$$$$$$$linux'
rsplit
S.rsplit(sep=None, maxsplit=-1) -> list of strings #从文件尾部开始按指定的分隔符切分字符串
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
>>> str1="hello/world/people"
>>> str1.rsplit("/")
['hello', 'world', 'people']
>>> str2="/etc/sysconfig/selinux"
>>> str2.rsplit("/")
['', 'etc', 'sysconfig', 'selinux']
expandtabs
S.expandtabs(tabsize=8) -> str #按照所给的参数把一个制表符转换成指定的空格,默认为转换为8个空格
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
>>> str1="hello\tworld"
>>> print(str1)
hello world
>>> str1.expandtabs()
'hello world'
>>> str1.expandtabs(8)
'hello world'
>>> str1.expandtabs(2)
'hello world'
>>> str1.expandtabs(12)
'hello world'
rindex
S.rindex(sub[, start[, end]]) -> int #返回子串在字符串中的索引值,未找到则抛出异常
Like S.rfind() but raise ValueError when the substring is not found.
>>> str1="abcdefghijklmn"
>>> str1.rindex("abc")
0
>>> str1.rindex("efg")
4
>>> str1.rindex("g")
6
>>> str1.rindex("m")
12
isprintable
S.isprintable() -> bool #字符里所有的字符都为可打印字符时返回True,否则返回False
Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
>>> str1=" "
>>> str2="hello world"
>>> str1.isprintable()
True
>>> str2.isprintable()
True
>>> str3="\t"
>>> print(str3)
>>> str3.isprintable()
False
splitlines
S.splitlines([keepends]) -> list of strings #按照换行符分隔字符串,返回分隔后的列表
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
>>> str1="hello \e world"
>>> print(str1)
hello \e world
>>> str1.splitlines()
['hello \\e world']
>>> type(str1.splitlines())
<class 'list'>
>>> str2="hello world"
>>> str2.splitlines()
['hello world']
format_map
S.format_map(mapping) -> str #格式化输出字符串
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
>>> str1="hello world {lang}"
>>> lang="python"
>>> print(str1.format_map(vars()))
hello world python
>>> str2="{os} {database} {webserver} python"
>>> os="linux"
>>> database="mysql"
>>> webserver="apache"
>>> print(str2.format_map(vars()))
linux mysql apache python
isnumeric
S.isnumeric() -> bool #字符串里所有的字符都是数字时返回True,否则返回False
Return True if there are only numeric characters in S,
False otherwise.
>>> str1="123456"
>>> str2="123.456"
>>> str3="hello world"
>>> str1.isnumeric()
True
>>> str2.isnumeric()
False
>>> str3.isnumeric()
False
partition
S.partition(sep) -> (head, sep, tail) #按照给定的字符分隔字符串,返回一个元组,如果给定的字符串有多个,则以第一个索引为准
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
>>> str1="hello world"
>>> str1.partition(" ")
('hello', ' ', 'world')
>>> str1.partition("l")
('he', 'l', 'lo world')
>>> str1.partition("w")
('hello ', 'w', 'orld')
rpartition
S.rpartition(sep) -> (head, sep, tail) #按照给定的字符分隔字符串,返回一个元组
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
>>> str1="abcdefg"
>>> str1.rpartition("b")
('a', 'b', 'cdefg')
>>> str1.rpartition("d")
('abc', 'd', 'efg')
>>> str1.rpartition("g")
('abcdef', 'g', '')
python字符串常用的方法解析的更多相关文章
- Python字符串常用的方法——真心觉得比java,c好用
# Strings have many methods wo can use rand_string=" life is a beautiful struggle " print( ...
- Python语言学习:字符串常用的方法
python字符串常用的方法 1. find( ):在字符串中搜索指定的值并返回它被找到的位置,如果没有找到,则返回-1 string.find(value,start,end) #value:必需, ...
- python字符串常用内置方法
python字符串常用内置方法 定义: 字符串是一个有序的字符的集合,用与存储和表示基本的文本信息. python中引号中间包含的就是字符串. # s1='hello world' # s2=&quo ...
- python字符串操作实方法大合集
python字符串操作实方法大合集,包括了几乎所有常用的python字符串操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下: #1.去空格及特殊符号 s.st ...
- python 字符串常用操作方法
python 字符串常用操作方法 python 字符串操作常用操作,如字符串的替换.删除.截取.赋值.连接.比较.查找.分割等 1.去除空格 str.strip():删除字符串两边的指定字符,括号的写 ...
- python3【基础】-字符串 常用的方法
字符串一个最重要的特性就是不可修改. name.capitalize() 首字母大写 name.casefold() 大写全部变小写 name.center(50,"-") 输出 ...
- Python—字符串常用函数
Python-字符串常用字符串 字符串是一种表示文本的数据类型,使用单引号和双引号及三引号表示 访问字符串中的值字符串的每个字符都对应一个下标,下标编号是从0开始 转义字符字符串的格式化输出切片常用函 ...
- python字符串常用操作方法
python字符串操作常用操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下. 1.去除空格str.strip():删除字符串两边的指定字符,括号的写入指定字符,默 ...
- Python 字符串格式化操作 - format方法
建议使用format()方法 字符串操作 对于 %, 官方以及给出这种格式化操作已经过时,在 Python 的未来版本中可能会消失. 在新代码中使用新的字符串格式.因此推荐大家使用format()来替 ...
随机推荐
- BZOJ:4820: [Sdoi2017]硬币游戏&&BZOJ:1444: [Jsoi2009]有趣的游戏(高斯消元求概率)
1444: [Jsoi2009]有趣的游戏 4820: [Sdoi2017]硬币游戏 这两道题都是关于不断随机生成字符后求出现给定字符串的概率的问题. 第一题数据范围较小,将串建成AC自动机以后,以A ...
- bzoj 1084;vijos 1191 [SCOI2005] 最大子矩阵
Description 这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大.注意:选出的k个子矩阵不能相互重叠. Input 第一行为n,m,k(1≤n≤100,1≤m≤2 ...
- [FZU1977] Pandora adventure
来学插头DP了= = GDKOI前觉得不会考数位DP,GDOI前觉得插头DP用不上.. 结果令人伤感>_< 这题并不用增加状态.. 只要在形成环的时候,让形成环的位置在最后一个必走点之后, ...
- noip级别数论?
TAT快noip了才开始去接触数论(真心不敢学..)这里做一下整理吧(都是些定义之类的东西= =) 欧几里德:gcd(a,b)=gcd(b,a%b);具体证明见百科? 扩展欧几里德: 求a*x+b*y ...
- BZOJ3930: [CQOI2015]选数
题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3930 容斥原理. 令l=(L-1)/k,r=R/k,这样找k的倍数就相当于找1的倍数. 设F[ ...
- NYoj289苹果(0-1背包)
苹果 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 ctest有n个苹果,要将它放入容量为v的背包.给出第i个苹果的大小和价钱,求出能放入背包的苹果的总价钱最大值. 输 ...
- linux系统下Vi编辑器或者Vim编辑器设置显示行号、自动缩进、调整tab键宽度的技巧?
工作中嫌vim 中一个tab键的宽度太大,linux系统默认,没改之前是一个tab键宽度是8个字符,想改成4个字符, 操作如下:(注意:这是在root用户下)cd ~vim .vimrc添加如下几行: ...
- c+(内存)
内存是程序运行的基础.所有正在运行的代码都保存在内存里面.内存需要处理各种各样的数据,包括键盘的数据.鼠标的数据.usb的数据.串口的数据.摄像头的数据,那么这些数据经过程序的处理之后,就要进行输出到 ...
- 最强PostMan使用教程(1)
最近需要测试产品中的REST API,无意中发现了PostMan这个chrome插件,把玩了一下,发现postman秉承了一贯以来google工具强大,易用的特质.独乐乐不如众乐乐,特此共享出来给大伙 ...
- git gui提交无法获知你的身份 20
刚刚学习,请说的详细一些,谢谢 callct | 浏览 3382 次 我有更好的答案 1条回答 你没有定义你的名字和邮箱.你打开git console/shell, #输入下面两句,并且替换成你的名字 ...