python基础-字符串常用函数介绍

字符串类型的常用函数介绍

字符串函数

str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

# 将字符串的首字符变为大写,其他字符变为小写,返回一个新的字符串
a = 'hello WORLD'
b = a.capitalize()
print(b)
print(id(a))
print(id(b))

str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

# 字符串按给定的宽度居中,并在两边填充字符
a = 'hello, 渔道'
b = a.center(50,'*')
print(b)

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

# 获取子串出现的次数
a = 'hello, 渔道 is very good, he is very nice'
b = a.count('is')
print(b)

str.encode(encoding=“utf-8”, errors=“strict”)

Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

# 将字符串 编码成 相应 encoding的字节对象。
a = 'hello,渔道'
b = a.encode(encoding='utf-8', errors="strict")
print(b)

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

# 判断字符串是否以指定后缀结束
one_suffix = '.mp4'
multi_suffix = ('.mp4', '.avi', '.wav')
a = "python基础-str.mp4"
b = a.endswith(one_suffix)
c = a.endswith(multi_suffix)
print(b)
print(c)

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

Note:
The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator

# 查找子串,返回子串的起始索引
a = 'hello,渔道'
b = a.find('渔道')
print(b)

str.isalnum()

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

# 判断字符串是否由数字和字母组成
a = '123dfkadf'
print(a.isalnum())
b = 'hello,渔道'
print(b.isalnum())

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

# 字符串连接
a = 'hello 渔道'
b = ', he is very nice'
print(''.join([a,b]))

str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped

str.rstrip([chars])

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

# lstrip 截掉字符串左边的空格或指定字符
a = '   hello, 渔道   '
b = a.lstrip()
print('{!r}'.format(b))
c = a.lstrip(' he')
print('{!r}'.format(c))
# rstrip 截掉字符串右边的空格或指定字符
d = a.rstrip()
print('{!r}'.format(d))
e = a.rstrip(' 道')
print('{!r}'.format(e))
# strip 截掉字符串两边的空格或指定字符
f = a.strip(' ')
print('{!r}'.format(f))
g = a.strip(' he道 ')
print('{!r}'.format(g))

str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

# 不指定分隔符
a = '1,2,3,4,5,6,7'
print(a.split())
# 指定分隔符
print(a.split(','))
# 指定分隔符,且指定最大分割次数
print(a.split(',',2))

# 如果不指定分隔符,且字符串中有空格,那么默认以空格进行分割
# 且字符串首尾的空格会被去掉
b = ' 1 2 3 4 5 6 7 '
print(b.split())

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

# 字符串替换
a = 'dkdfjakjfa'
b = a.replace('a','A')
print(b)

static str.maketrans(x[, y[, z]])

This static method returns a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be 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.

str.translate(table)

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself.

# 制作转换表
a = 'abcdefg'
b = '1234567'
c = str.maketrans(a,b)
print(c)

d = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7'}
d1 = str.maketrans(d)
print(d1)

# 进行转换
aa = "yudao is a good platform to learn python"
e = aa.translate(c)
print(e)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sif_666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值