Python 编程 | 连载 05 - 字符串操作

简介: Python 编程 | 连载 05 - 字符串操作

一、字符串 String 操作

Python中一切皆对象,而每个对象都拥有各自的属性与方法,对象的特点就是它的属性,对象拥有的功能就是它的方法

capitalize 函数

capitalize方法的作用是将字符串首字母大写其他字母小写

capitalize()函数是字符串对象的一个函数,只有字符串才能调用,方法的参数为空并返回一个新的字符串;原字符串不会受到影响

d50fcf0177484270ba9e59494e291f03_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

在python-hero项目中新增capitalize.py文件

name = 'thor'
info = 'stark 斯塔克'
nick_name = '蜘蛛侠 Peter'
number_str = '9527'
new_name = name.capitalize()
new_info = info.capitalize()
new_nick_name = nick_name.capitalize()
new_number_str = number_str.capitalize()
print(new_name)
print("name变量的值:" + name)
print(new_info)
print("info变量的值:" + info)
print(new_nick_name)
print("nick_name变量的值:" + nick_name)
print(new_number_str)
print("number_str变量的值:" + number_str)
复制代码

执行Python脚本

583cb34042654ab8b7c7d17ebb54915a_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

根据控制台输出,capitalize方法将首字母都变成了大写,而原字符串不变

capitalize的注意事项有:

  • 只对第一个字母有效
  • 只对字母有效
  • 字母已经是大写则不做任何改变

casefold 与 lower 函数

casefold函数的功能与lower函数的功能一致,作用是将字符串中所有的字符全部小写,并返回一个新的字符串,且不用填写任何参数

casefold和lower只对字符串中的字母有效,其他字符无效,且如果字符已经全部都是小写,则调用方法不会有任何变化

casefold在python3.3之后才引入的,lower在python2版本中就存在 lower将英文字母小写,其他语言则无法处理 casefold可以将更多语种进行小写处理

name = 'PETER'
info = 'How Are You'
info_ch = '你好啊'
info_empty = ''
new_name = name.casefold()
new_info = info.casefold()
new_info_ch = info_ch.casefold()
new_info_empty = info_empty.casefold()
new_name_lower = name.lower()
new_info_lower = info.lower()
new_info_ch_lower = new_info_ch.lower()
new_info_empty_lower = info_empty.lower()
print(new_name)
print(new_info)
print(new_info_ch)
print(new_info_empty)
print('-------------')
print(new_name_lower)
print(new_info_lower)
print(new_info_ch_lower)
print(new_info_empty_lower)
print('-------------')
复制代码

19b0f057c8cf483aadf8d0e939167ffb_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

对英文casefold和lower对英文语言的作用是一样的,作用于空字符串不会报错且原字符串不变

upper 函数

upper函数的作用是将字符串全体大写,并返回新的字符串,参数为空;upper函数只会作用于字符串中的字母,如果字母已经是大写则无效。

info = 'Hello Python!'
message = 'this is peter, 18 years old'
new_info = info.upper()
new_message = message.upper()
print(new_info)
print(new_message)
复制代码

90f19d36d06e4a6ba2d2a06876b570be_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

swapcase 函数

swapcase是大小写有关中的最后一个函数,该函数的作用是将字符串中的大小写字母进行转换,该函数返回一个新的字符串,传递的参数为空。swapcase函数只针对字符串中的字符有效

info_01 = 'python is The World Best LANGUAGE'
info_02 = 'python web is VERY IMPORTANT'
new_info_01 = info_01.swapcase()
new_info_02 = info_02.swapcase()
print(new_info_01)
print(new_info_02)
复制代码

b433db521ff7469ba2005e1bef370a3c_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

zfill 函数

zfill函数为字符串定义长度,如果字符串长度不满足定义的长度,则用0填补;该函数返回一个新的字符串,并且需要传入一个参数既字符串的长度;zfill函数的使用与字符串的字符无关并且如果定义长度小于当前字符串的长度,则不发生变化

info = 'python'
if __name__ == '__main__':
    print(len(info))
    print(info.zfill(3))
    print(info.zfill(10))
复制代码

130f98f63b2446e190f6d10c72a64ef3_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

count 函数

count 函数返回当前字符串中指定字符的个数,需要传入一个字符作为参数并返回一个整型数据,如果查询的元素不再字符串中就返回0

zen = '''
    The Zen of Python, by Tim Peters
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    '''
is_count = zen.count('is')
print(is_count)
to_count = zen.count('to')
print(to_count)
of_count = zen.count('of')
print(of_count)
复制代码

558de06129ad413095a36f68e84f457e_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

startswith 和 endswith 函数

startswith函数的功能是判断字符串开始位是否是指定的字符串,endswith函数式判断字符串是否以指定的字符串结束,这两个函数都返回布尔值。

info = 'i am iron man'
msg = 'today is monday'
res_01 = info.startswith('i')
print(res_01)
res_02 = msg.startswith('t')
print(res_02)
res_03 = info.endswith('n')
print(res_03)
res_04 = msg.endswith('a')
print(res_04)
复制代码

4daba93a22ae4a7896753e91dec8627e_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

find 函数与 index  函数

find与index都是返回指定成员在字符串中的位置,参数为要查询的字符,返回一个整形;如果find找不到指定元素返回-1,如果index找不到指定元素则会报错

info = 'python is the world best language'
res_01 = info.find('o')
print(res_01)
res_02 = info.index('o')
print(res_02)
res_03 = info.find('go')
print(res_03)
res_04 = info.index('go')
print(res_04)
复制代码

a615e4503f494995b6354544862bd8e9_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

strip、lstrip、rstrip 函数

strip 函数可以去除字符串左右两边的指定元素,默认去除空格;返回一个新的字符串,参数为指定要去除的字符,默认为空格。

注意事项:

  • 传入的元素如果不再开头或者结尾则无效
  • lstrip仅仅去掉字符串开头的指定元素或者空格
  • rstrip仅仅去除字符串结尾的指定元素或者空格
message = '  ---With great power comes great responsibility---   '
message_01 = message.strip()
print(message_01)
message_02 = message_01.strip('-')
print(message_02)
message_03 = message_02.lstrip('W')
print(message_03)
message_04 = message_03.rstrip('y')
print(message_04)
复制代码

76903e7d80b24085956af5857353835a_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

replace 函数

replace函数可以将字符串中指定的元素(old)替换为另一个指定的元素(new),并可以指定替换的数量(max),replace函数需要传入三个参数并返回一个新的字符串,替换数量默认为替换全部,并且从左往右替换,如果要替换的元素字符串中不存在,则字符串不会发生变化

new_str = str.replace(old, new, max)
复制代码
code = 'Who is The strongest Avenger'
code_01 = code.replace('Who', 'Thor')
print(code_01)
code_02 = code.replace('e', 'E')
print(code_02)
code_03 = code.replace('e', 'E', 1)
print(code_03)
code_04 = code.replace('who', 'Hulk')
print(code_04)
复制代码

e802359bd87142c8bc55b656519e7f8e_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

返回 bool 类型的函数

字符串中返回值为bool类型的有以下几个函数

  • isspace:判断字符串是否由空格组成,无须传递参数
  • istitle:判断字符串是否是一个标题类型,无须传递参数
  • isupper:判断字符串中的字符是否都是大写,无须传递参数
  • islower:判断字符串中的字符是否都是小写,无须传递参数

注意:

  • 由空格组成的字串不是空字符串
  • title就是有多个单词组成,每个单词的首字母大写
  • title函数只能用于英文
print('-----isspace函数-----')
print('  '.isspace())
print('HULK'.isspace())
print('STARK '.isspace())
print('-----istitle函数-----')
print('Stark Industry'.istitle())
print('the seven'.istitle())
print('-----isupper函数-----')
print('VISION'.isupper())
print('Thor Odin'.isupper())
print('-----islower函数-----')
print('Tony'.islower())
print('ok'.islower())
复制代码

733699fd86f64f21a512033ece23d101_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

这几个函数使用频率相对较低。


相关文章
|
8天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
8天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
11天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
11天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
30天前
|
大数据 Python
使用Python查找字符串中包含的多个元素
本文介绍了Python中查找字符串子串的方法,从基础的`in`关键字到使用循环和条件判断处理多个子串,再到利用正则表达式`re模块`进行复杂模式匹配。文中通过实例展示了如何提取用户信息字符串中的用户名、邮箱和电话号码,并提出了优化策略,如预编译正则表达式和使用生成器处理大数据。
20 1
|
28天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
157 0
|
1天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
14 0
|
2天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
22 0
|
3天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
11天前
|
Python
171: 字符串的倒序(python)
171: 字符串的倒序(python)

热门文章

最新文章