Python 中 str 基本类型方法

1. str 字符串类型

字符串一旦创建,人生格言便是:“誓死方休”。

无论什么语言,字符串一旦创建,就会占用内存。就算是修改内容,也是重新分配内存进行赋值。字符串一旦创建,就有固定的内容,就有指定的内存空间,内容就不会变,一变就会重新赋值,则指定的内存空间就会改变,就算外表一样,实质也不一样。

2. str 字符串的基本方法

2.1 大小写

capitalize(self, *args, **kwargs):
casefold(self, *args, **kwargs)
islower(self, *args, **kwargs)
isupper(self, *args, **kwargs)
lower(self, *args, **kwargs)
upper(self, *args, **kwargs)
swapcase(self, *args, **kwargs)
capitalize: 首字母大写,其他字母小写(Return a capitalized version of the string.More specifically, make the first character have upper case and the rest lower case.)
casefold: 转化为小写字母(Return a version of the string suitable for caseless comparisons.)
lower: 转化为小写字母(Return a copy of the string converted to lowercase.)
upper: 转化为大写字母(Return a copy of the string converted to uppercase.)
islower: 判断是否为小写字母(Return True if the string is a lowercase string, False otherwise.)
isupper: 判断是否为大写字母(Return True if the string is an uppercase string, False otherwise.)
swapcase: 大小写切换(Convert uppercase characters to lowercase and lowercase characters to uppercase.)

lower() 方法只对 ASCII 编码,也就是 “A-Z” 有效,对于其他语言中把大写转换为小写的情况只能用 casefold() 方法。

2.2 增减

center(self, *args, **kwargs)
ljust(self, *args, **kwargs)
rjust(self, *args, **kwargs)
zfill(self, *args, **kwargs)
expandtabs(self, *args, **kwargs)
join(self, ab=None, pq=None, rs=None)
lstrip(self, *args, **kwargs)
rstrip(self, *args, **kwargs)
strip(self, *args, **kwargs)
添加:
	center: 多出来的指定地方由符号填充到字符串两边(Return a centered string of length width.Padding is done using the specified fill character (default is a space).)
	ljust: 多出来的指定地方由符号填充到字符串右边(Return a left-justified string of length width. Padding is done using the specified fill character (default is a space).)
	rjust: 多出来的指定地方由符号填充到字符串左边(Return a right-justified string of length width. Padding is done using the specified fill character (default is a space).)
	zfill: 多出来的指定地方由空格添加到字符串前面(Pad a numeric string with zeros on the left, to fill a field of the given width. The string is never truncated.)
	expandtabs: 以 \t 为基础分割,规定所占多大的位置(Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed.)
	join: 将字符串中每个字符之间加上一个空格(The string whose method is called is inserted in between each given string. The result is returned as a new string.)
减少:
	lstrip: 将字符串连续去掉左边含有指定字符串中的子字符串(Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead.)
	rstrip: 将字符串连续去掉右边含有指定字符串中的子字符串(Return a copy of the string with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.)
	strip: 将字符串连续去掉两边含有指定字符串中的子字符串(Return a copy of the string with leading and trailing whitespace remove. If chars is given and not None, remove characters in chars instead.)

其中 center(), ljust(), rjust() 默认填充为空格
其中 lstrip(), rstrip(), strip() 默认是去掉空格,包括 \t 和 \n
在这里插入图片描述

2.3 修改

title(self, *args, **kwargs)
format(self, *args, **kwargs)
format_map(self, mapping)
maketrans(self, *args, **kwargs)
translate(self, *args, **kwargs)
replace(self, *args, **kwargs)
partition(self, *args, **kwargs)
rpartition(self, *args, **kwargs)
split(self, *args, **kwargs)
rsplit(self, *args, **kwargs)
splitlines(self, *args, **kwargs)
title: 把字符串设为标题形式(Return a version of the string where each word is titlecased. More specifically, words start with uppercased characters and all remaining cased characters have lower case.)
format: 指定改变子字符串中大括号的内容(Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').)
format_map: 指定改变子字符串中大括号的内容(Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').)
maketrans: 指定映射关系,与 translate() 方法连用(Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.)
translate: 以 maketrans() 规定的映射翻译字符串(Replace each character in the string using the given translation table. [table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.] The table must implement lookup/indexing via __getitem__, for instance a dictionary or list.  If this operation raises LookupError, the character is left untouched.  Characters mapped to None are deleted.)
replace: 指定替换子字符串和个数(Return a copy with all occurrences of substring old replaced by new. [count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.] If the optional argument count is given, only the first count occurrences are replaced.)
partition: 从字符串左边开始指定分裂三分(Partition the string into three parts using the given separator. This will search for the separator in the string.  If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing the original string and two empty strings.)
rpartition: 从字符串右边开始指定分裂三分(Partition the string into three parts using the given separator. This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing two empty strings and the original string.)
split: 从字符串左边开始指定分裂个数(Return a list of the words in the string, using sep as the delimiter string. [sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.] [maxsplit Maximum number of splits to do. -1 (the default value) means no limit.])
rsplit: 从字符串右边开始指定分裂个数(Return a list of the words in the string, using sep as the delimiter string. [sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result.] [maxsplit Maximum number of splits to do. -1 (the default value) means no limit.] Splits are done starting at the end of the string and working to the front.)
splitlines: 以 \n 分裂字符串,是否保留 \n(Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.)

format(), format_map() 区别在于,如图:
在这里插入图片描述

maketrans(), translate() 连用,如图:
在这里插入图片描述

replace(), split(), rsplit() 可以指定替换或者分裂的符号及个数,而 partition(), rpartition() 分裂3分可以指定符号,splitlines() 全部分裂且符号位 \n

2.4 查询

count(self, sub, start=None, end=None)
index(self, sub, start=None, end=None)
rindex(self, sub, start=None, end=None)
find(self, sub, start=None, end=None)
rfind(self, sub, start=None, end=None)
startswith(self, prefix, start=None, end=None)
endswith(self, suffix, start=None, end=None)
count: 指定范围查询指定字符串的个数(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.)
index: 从字符串左边开始指定所给子字符串的索引(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. Raises ValueError when the substring is not found.)
rindex: 从字符串右边开始指定所给子字符串的索引(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. Raises ValueError when the substring is not found.)
find: 从字符串左边开始指定所给子字符串的索引(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.)
rfind: 从字符串右边开始指定所给子字符串的索引(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. Return -1 on failure.)
startswith: 判断是否以所给字符串开头(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.)
endswith: 判断是否以所给字符串结尾(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.)

index(), rindex() 与 find(), rfind() 区别在于:指定子字符没有在字符串当中,index(), rindex() 返回的是报错,而 find(), rfind() 返回的结果是 -1

2.4 判断

先认识认识几个简单的单词:alphabet 字母表,numeric 数字的,digit 数字,decimal 十进制的,identifier 标识符,

isalpha(self, *args, **kwargs)
isdigit(self, *args, **kwargs)
isnumeric(self, *args, **kwargs)
isalnum(self, *args, **kwargs)
isspace(self, *args, **kwargs)
istitle(self, *args, **kwargs)
isdecimal(self, *args, **kwargs)
isidentifier(self, *args, **kwargs)
isprintable(self, *args, **kwargs)
islower(self, *args, **kwargs)
isupper(self, *args, **kwargs)

上面的几个就比较简单,唯一要说的就是 isdigit()isnumeric() 的区别,如图:
在这里插入图片描述

  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值