python删除字符串中某个字符,用replace()方法来处理

news/2024/7/24 4:51:06

Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法
replace()方法语法:

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

参数
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次

返回值
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

实例

str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

运行结果:

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

特别说明:str被replace之后,str本身没有发生改变

参考:replace的用法


http://www.niftyadmin.cn/n/1520619.html

相关文章

python判断某个字符串中是否包含某个子字符串,方法:if ’str1‘ in str

使用in方法 实例: str1hello china! if china in str1:print(yes) else:print(no)运行结果: yes参考:链接

leetcode --2.两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字…

Leetcode3.无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb"输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最…

Leetcode7.整数翻转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例 1: 输入: 123 输出: 321示例 2: 输入: -123输出: -321示例 3: 输入: 120 输出: 21注意: 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − …

centos7查看yum仓库下所有的rpm包

centos7查看yum仓库下所有的rpm包 # 列出所有仓库中的rpm yum list # 列出某一仓库中的rpm yum repo-pkgs <repo-name> listrepo-pkgs的意思是将yum仓库当作安装包的组&#xff08;Minimal Install、GNOME Desktop等&#xff09;来看待&#xff0c;这样就能后接包或组才…

c++如何输入一个不定长的字符串数组

#include<iostream> #include<vector> #include<string.h> using namespace std;int main(){vector<string> strs;string s;while(cin>>s){strs.push_back(s);}cout<<strs.size();return 0; }每次输入字符串敲一下回车&#xff0c;继续输…

leetcode.20.有效的括号

文章目录题目&#xff1a;leetcode.20.有效的括号基本思想&#xff1a;栈题目&#xff1a;leetcode.20.有效的括号 给定一个只包括 ‘(’&#xff0c;’)’&#xff0c;’{’&#xff0c;’}’&#xff0c;’[’&#xff0c;’]’ 的字符串&#xff0c;判断字符串是否有效。 …