0
点赞
收藏
分享

微信扫一扫

python内置函数系列之str(一)(持续更新)

大沈投资笔记 2022-03-24 阅读 66
python

python内置函数之str(一),持续更新。

  1. capitalize

介绍:

        """
        Return a capitalized version of the string.
        
        More specifically, make the first character have upper case and the rest lower
        case.
        """

即:

返回字符串的大写版本。更具体地说,使第一个字符为大写,其余为小写。

  • 参数:
    无。

  • 返回值:
    一个新字符串。

代码示例:

a = "apple"
x = a.capitalize()  # 等价于x = str.capitalize(a)
# 调用该方法后,返回一个新字符串,原字符串不改变
print(x, a)
'''结果:
Apple apple
'''

2.upper

介绍:

 """ Return a copy of the string converted to uppercase. """

即:
返回转换为大写的字符串的副本。
(将所有小写形式的字符转成大写并返回一个新字符串)

  • 参数
    无。

  • 返回值

    一个新字符串。

代码示例:

a = "snfsahgasngkasajl214sfmlkkp124"
x = a.upper()

print(x)

'''结果:
SNFSAHGASNGKASAJL214SFMLKKP124
'''
  1. lower

介绍:

""" Return a copy of the string converted to lowercase. """

即:

返回转换为小写的字符串的副本。

  • 参数:
    无。

  • 返回值:
    一个新字符串。

示例代码:

a = "ApplE"
x = a.lower()  
# 调用该方法后,返回一个新字符串,原字符串不改变
print(x, a)
'''结果:
Apple ApplE
'''
  1. casefold

此方法是Python3.3版本之后引入的,其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。

两者的区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。

  • 参数:
    无。
  • 返回值:
    一个新字符串。
a = "ApplE and ß"  # ß是德语中的一个字母,其小写形式为ss
x = a.casefold()
# 调用该方法后,返回一个新字符串,原字符串不改变
print(x)
'''结果:
apple and ss
'''
  1. center

介绍:

"""
Return a centered string of length width.
        
Padding is done using the specified fill character (default is a space).
"""

即:
返回一个居中的长度宽度的字符串。使用指定的填充字符完成填充(默认为空格)。

  • 参数:

width – 字符串的总宽度。

fillchar – 填充字符。(不传则默认为空字符)

代码示例:

x = a.center(20, '$')
y = a.center(20)
# 调用该方法后,返回一个新字符串,原字符串不改变
print(x)
print(y)
'''结果:
$$$$$$$money$$$$$$$$
       money        
'''
  1. 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 areinterpreted as in slice notation.
"""

翻译:
S.count(sub[, start[, end]]) -> int 返回字符串 S[start:end] 中子字符串 sub 不重叠出现的次数。可选参数 start 和 end 被解释为 slice符号。

简单来说:
该方法用于统计字符在字符串中的出现次数。

  • 参数:
  1. sub - - - - 需要统计的字符或字符串。
  2. start - - - - -开始查找的初始位置
    (默认为第一个字符,第一个字符索引值为0。)
  3. end - - - - 结束查找的末位置。
    (默认为字符串的最后一个位置。)
  • 返回值:

一个整型数字,代表符合区间的出现次数。

代码示例:

a = "snfsahgasngkasajl214sfmlkkp124"
x = a.count('s', 5, 15)
y = a.count('s', a.find('l'), a.find('p'))  # 利用find方法与此方法结合
print(x)
print(y)
'''结果:
2
1
'''

着重关注find方法与此方法结合,很实用。

举报

相关推荐

0 条评论