当前位置: 首页 > news >正文

成为Python砖家(2): str 最常用的8大方法

str 类最常用的8个方法

  • str.lower()
  • str.upper()
  • str.split(sep=None, maxsplit=-1)
  • str.count(sub[, start[, end]])
  • str.replace(old, new[, count])
  • str.center(width[, fillchar])
  • str.strip([chars])
  • str.join(iterable)

查询方法的文档

根据 成为Python砖家(1): 在本地查询Python HTML文档 提供的方法,在本地查询文档,得到对应函数的说明。
在这里插入图片描述

在这里插入图片描述

8大方法使用举例

# Python3 str 最常用的8大方法
# author: https://github.com/zchrissirhcz
# ref: https://www.bilibili.com/video/BV1JL4y1x7xC/?p=15# h1/8
# str.lower() 返回字符串的副本,全部字符为小写
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.lower
# Return a copy of the string with all the cased characters [4] converted to lowercase.
s = "HELLO WORLD"
t = s.lower()
print(t)# h2/8
# str.uppper() 返回字符串的副本,全部字符为大写
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.upper
# Return a copy of the string with all the cased characters [4] converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).
u = "hello world"
v = u.upper()
print(v)
print(v.isupper())# h3/8
# str.split(sep=None, maxsplit=-1) 返回一个列表,由 str 根据 sep 被分割的部分组成
# sep 可以是多个字符, 它们的整体被当作分隔符
# maxsplit表示分隔的数量,默认值-1表示分隔所有的;如果是大于0的取值,那么最多可以得到 maxsplit+1 个元素的 list,最后一个是没有被分割的字符串
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.split
# 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).
#
# If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters as a single delimiter (to split with multiple delimiters, use re.split()). Splitting an empty string with a specified separator returns [''].
s1 = "The cat sat on the mat, watching the birds through the window while the sun set slowly beyond the horizon."
t1 = s1.split("the")
t2 = s1.split("the", 2)
print("t1", t1)
print("t2", t2)# h4/8
# str.count(sub[, start[, end]]) 返回字串 sub 在 str 中出现的次数
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.count
# 可选参数 start 和 end 表示范围,相当于 str[start:end]. 注意,这并不会包含 str[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.
#
# If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.
s1 = "hello world"
cnt = s1.count('o')
print(f"number of 'o' in '{s1}' = {cnt}")
cnt2 = s1.count('') # 12
print(f"number of '' in '{s1}' = {cnt2}")
cnt3 = s1.count('o', 0, 4)
print(cnt3) # 0
cnt4 = s1.count('o', 0, 5)
print(cnt4) # 1s2 = "ababab"
cnt5 = s2.count("ab")
print(cnt5) # 3# h5/8
# str.replace(old, new[, count])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.replace
# 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.
# 返回字符串 str 的副本, 所有 old 被替换为 new。 如果给了 count 参数,那么只替换前 count 次
s1 = "hello world"
s2 = s1.replace("world", "python")
print(f"s2: {s2}") # hello python# h6/8
# str.center(width[, fillchar])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.center
# 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).
# 返回字符串 str 根据宽度 width 在左右两侧均等填充 fillchar 后的字符串
# 如果没指定填充字符, 则使用空格填充
# 如果原始字符串长度大于指定的参数 width,那么不填充, 直接返回原始字符串
s1 = "python"
s2 = s1.center(20, "=")
print(s2) # =======python=======# h7/8
# str.strip([chars])
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.strip
# 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.
# 从字符串左右两侧,删除 chars 里出现的字符
# 参数 chars 类型是字符串,但它里面每个字符都被均等对待,任何在 chars 里的字符,都将被剔除
# 如果 chars 参数没指定,则空白字符会被剔除
s1 = "www.example.com"
s2 = s1.strip('comw')
print(s2) # .example.s3 = "= python= "
s4 = s3.strip(" =np")
print(s4) # "ytho"# h8/8
# str.join(iterable)
# file:///Users/zz/Documents/python-3.12.5-docs-html/library/stdtypes.html#str.join
# 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.
# 返回一个字符串,是 iterable 参数中的元素的相互拼接,拼接的粘连符号是 str 本身
s1 = ["1", "2", "3"]
s2 = ','.join(s1)
print(s2) # 1,2,3

相关文章:

成为Python砖家(2): str 最常用的8大方法

str 类最常用的8个方法 str.lower()str.upper()str.split(sepNone, maxsplit-1)str.count(sub[, start[, end]])str.replace(old, new[, count])str.center(width[, fillchar])str.strip([chars])str.join(iterable) 查询方法的文档 根据 成为Python砖家(1): 在本地查询Pyth…...

深入理解JVM运行时数据区(内存布局 )5大部分 | 异常讨论

前言: JVM运行时数据区(内存布局)是Java程序执行时用于存储各种数据的内存区域。这些区域在JVM启动时被创建,并在JVM关闭时销毁。它们的布局和管理方式对Java程序的性能和稳定性有着重要影响。 目录 一、由以下5大部分组成 1.…...

JAVA根据表名获取Oracle表结构信息

响应实体封装 import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor;/*** author CQY* version 1.0* date 2024/8/15 16:33**/ Data NoArgsConstructor AllArgsConstructor Builder public class OracleTableInfo …...

网络性能优化

网络性能优化是确保网络稳定性、速度和可靠性的关键步骤。优化过程通常包括诊断问题、识别瓶颈以及实施具体的解决方案。以下是关于如何进行网络性能优化的详细指南: 一、问题诊断 网络性能监控 网络流量分析工具:使用Wireshark、NetFlow、Ntop等工具监…...

[C++String]接口解读,深拷贝和浅拷贝,string的模拟实现

💖💖💖欢迎来到我的博客,我是anmory💖💖💖 又和大家见面了 欢迎来到C探索系列 作为一个程序员你不能不掌握的知识 先来自我推荐一波 个人网站欢迎访问以及捐款 推荐阅读 如何低成本搭建个人网站…...

理性看待、正确理解 AI 中的 Scaling “laws”

编者按:LLMs 规模和性能的不断提升,让人们不禁产生疑问:这种趋势是否能一直持续下去?我们是否能通过不断扩大模型规模最终实现通用人工智能(AGI)?回答这些问题对于理解 AI 的未来发展轨迹至关重…...

【OCR 学习笔记】二值化——全局阈值方法

二值化——全局阈值方法 固定阈值方法Otsu算法在OpenCV中的实现固定阈值Otsu算法 图像二值化(Image Binarization)是指将像素点的灰度值设为0或255,使图像呈现明显的黑白效果。二值化一方面减少了数据维度,另一方面通过排除原图中…...

Java - IDEA开发

使用IDEA开发Java程序步骤: 创建工程 Project;创建模块 Module;创建包 Package;创建类;编写代码; 如何查看JDK版本 Package介绍: package是将项目中的各种文件,比如源代码、编译生成的字节码、配置文件、…...

Oracle(62)什么是内存优化表(In-Memory Table)?

内存优化表(In-Memory Table)是指将表的数据存储在内存中,以提高数据访问和查询性能的一种技术。内存优化表通过利用内存的高速访问特性,显著减少I/O操作的延迟,提升数据处理的速度。这种技术在需要高性能数据处理的应…...

#window家庭版安装hyper-v#

由于window 11 家庭版没有hyper-v虚拟机服务,则需要安装一下,使用如下操作 1:新建一个txt文件,拷贝如下脚本到里面 pushd "%\~dp0" dir /b %SystemRoot%\servicing\Packages\*Hyper-V*.mum >hyper-v.txt for /f %%i in (findst…...

【云原生】Pass容器研发基础——汇总篇

云原生基础汇总 系列综述: 💞目的:本系列是个人整理为了云计算学习的,整理期间苛求每个知识点,平衡理解简易度与深入程度。 🥰来源:每个知识点的修正和深入主要参考各平台大佬的文章&#xff0c…...

【Py/Java/C++三种语言详解】LeetCode743、网络延迟时间【单源最短路问题Djikstra算法】

可上 欧弟OJ系统 练习华子OD、大厂真题 绿色聊天软件戳 od1441了解算法冲刺训练(备注【CSDN】否则不通过) 文章目录 相关推荐阅读一、题目描述二、题目解析三、参考代码PythonJavaC 时空复杂度 华为OD算法/大厂面试高频题算法练习冲刺训练 相关推荐阅读 …...

交替输出

交替输出 题目:线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc wait notify 版 public class SyncWaitNotify {private volatile int flag;private volatile int loopNumber;public SyncWaitNo…...

JS(三)——更改html内数据

获取 DOM 元素&#xff0c;然后修改其属性或内容。使用 getElementById 方法获取特定 ID 的元素&#xff1a; <p id"myParagraph">这是初始的文本</p> const paragraph document.getElementById(myParagraph); paragraph.innerHTML 这是修改后的文本…...

CSS小玩意儿:文字适配背景

一&#xff0c;效果 二&#xff0c;代码 1&#xff0c;搭个框架 添加一张背景图片&#xff0c;在图片中显示一行文字。 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" conte…...

C++:平衡二叉搜索树之红黑树

一、红黑树的概念 红黑树&#xff0c; 和AVL都是二叉搜索树&#xff0c; 红黑树通过在每个节点上增加一个储存位表示节点的颜色&#xff0c; 可以是RED或者BLACK&#xff0c; 通过任何一条从根到叶子的路径上各个节点着色方式的限制&#xff0c;红黑树能够确保没有一条路径会比…...

CentOS 7 系统优化

CentOS 7 系统优化 1、配置YUM源 阿里云的YUM源配置&#xff1a; CentOS 7使用以下命令&#xff1a; sudo wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repoCentOS 8使用以下命令&#xff1a; sudo wget -O /etc/yum.repos.d/CentOS…...

扫雷游戏——附源代码

扫雷游戏的源代码比较简单&#xff0c;不设计比较复杂的代码&#xff0c;主要是多个函数的组合&#xff0c;每个函数执行自己的功能&#xff0c;最终支持游戏的完成。 1.菜单 我们需要一个提醒信息来让用户进行选择。 void menu() {printf("***********************\n&…...

Vue3列表(List)

效果如下图&#xff1a;在线预览 APIs List 参数说明类型默认值bordered是否展示边框booleanfalsevertical是否使用竖直样式booleanfalsesplit是否展示分割线booleantruesize列表尺寸‘small’ | ‘middle’ | ‘large’‘middle’loading是否加载中booleanfalsehoverable是否…...

HarmonyOS NEXT - Navigation组件封装BaseNavigation

demo 地址: https://github.com/iotjin/JhHarmonyDemo 代码不定时更新&#xff0c;请前往github查看最新代码 在demo中这些组件和工具类都通过module实现了&#xff0c;具体可以参考HarmonyOS NEXT - 通过 module 模块化引用公共组件和utils 官方介绍 组件导航 (Navigation)(推…...

云原生核心技术 (7/12): K8s 核心概念白话解读(上):Pod 和 Deployment 究竟是什么?

大家好&#xff0c;欢迎来到《云原生核心技术》系列的第七篇&#xff01; 在上一篇&#xff0c;我们成功地使用 Minikube 或 kind 在自己的电脑上搭建起了一个迷你但功能完备的 Kubernetes 集群。现在&#xff0c;我们就像一个拥有了一块崭新数字土地的农场主&#xff0c;是时…...

智慧医疗能源事业线深度画像分析(上)

引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...

Spark 之 入门讲解详细版(1)

1、简介 1.1 Spark简介 Spark是加州大学伯克利分校AMP实验室&#xff08;Algorithms, Machines, and People Lab&#xff09;开发通用内存并行计算框架。Spark在2013年6月进入Apache成为孵化项目&#xff0c;8个月后成为Apache顶级项目&#xff0c;速度之快足见过人之处&…...

Leetcode 3576. Transform Array to All Equal Elements

Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接&#xff1a;3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到&#xf…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

如何在看板中有效管理突发紧急任务

在看板中有效管理突发紧急任务需要&#xff1a;设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP&#xff08;Work-in-Progress&#xff09;弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中&#xff0c;设立专门的紧急任务通道尤为重要&#xff0c;这能…...

基础测试工具使用经验

背景 vtune&#xff0c;perf, nsight system等基础测试工具&#xff0c;都是用过的&#xff0c;但是没有记录&#xff0c;都逐渐忘了。所以写这篇博客总结记录一下&#xff0c;只要以后发现新的用法&#xff0c;就记得来编辑补充一下 perf 比较基础的用法&#xff1a; 先改这…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕&#xff0c;#AI 监考一度冲上热搜。当AI深度融入高考&#xff0c;#时间同步 不再是辅助功能&#xff0c;而是决定AI监考系统成败的“生命线”。 AI亮相2025高考&#xff0c;40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕&#xff0c;江西、…...

蓝桥杯 冶炼金属

原题目链接 &#x1f527; 冶炼金属转换率推测题解 &#x1f4dc; 原题描述 小蓝有一个神奇的炉子用于将普通金属 O O O 冶炼成为一种特殊金属 X X X。这个炉子有一个属性叫转换率 V V V&#xff0c;是一个正整数&#xff0c;表示每 V V V 个普通金属 O O O 可以冶炼出 …...

视频行为标注工具BehaviLabel(源码+使用介绍+Windows.Exe版本)

前言&#xff1a; 最近在做行为检测相关的模型&#xff0c;用的是时空图卷积网络&#xff08;STGCN&#xff09;&#xff0c;但原有kinetic-400数据集数据质量较低&#xff0c;需要进行细粒度的标注&#xff0c;同时粗略搜了下已有开源工具基本都集中于图像分割这块&#xff0c…...