Python字符串方法用示例解释
字符串查找方法 (String Find Method)
There are two options for finding a substring within a string in Python, find()
and rfind()
.
在Python中的字符串中有两个选项可以找到子字符串: find()
和rfind()
。
Each will return the position that the substring is found at. The difference between the two is that find()
returns the lowest position, and rfind()
returns the highest position.
每个都将返回找到子字符串的位置。 两者之间的区别在于find()
返回最低位置,而rfind()
返回最高位置。
Optional start and end arguments can be provided to limit the search for the substring to within portions of the string.
可以提供可选的开始和结束参数,以将对子字符串的搜索限制在字符串的一部分之内。
Example:
例:
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!"
>>> string.find('you')
6
>>> string.rfind('you')
42
If the substring is not found, -1 is returned.
如果未找到子字符串,则返回-1。
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!"
>>> string.find('you', 43) # find 'you' in string anywhere from position 43 to the end of the string
-1
More Information:
更多信息:
String methods documentation.
字符串方法文档 。
字符串连接方法 (String Join Method)
The str.join(iterable)
method is used to join all elements in an iterable
with a specified string str
. If the iterable contains any non-string values, it raises a TypeError exception.
str.join(iterable)
方法用于使用指定的字符串str
连接iterable
所有元素。 如果该iterable包含任何非字符串值,则将引发TypeError异常。
iterable
: All iterables of string. Could a list of strings, tuple of string or even a plain string.
iterable
:字符串的所有iterables。 可能是字符串列表,字符串元组甚至是纯字符串。
例子 (Examples)
Join a ist of strings with ":"
用":"
字符串ist
print ":".join(["freeCodeCamp", "is", "fun"])
Output
输出量
freeCodeCamp:is:fun
Join a tuple of strings with " and "
用" and "
连接一个字符串元组
print " and ".join(["A", "B", "C"])
Output
输出量
A and B and C
Insert a " "
after every character in a string
在字符串中的每个字符后插入" "
print " ".join("freeCodeCamp")
Output:
输出:
f r e e C o d e C a m p
Joining with empty string.
用空字符串连接。
list1 = ['p','r','o','g','r','a','m']
print("".join(list1))
Output:
输出:
program
Joining with sets.
套组连接。
test = {'2', '1', '3'}
s = ', '
print(s.join(test))
Output:
输出:
2, 3, 1
更多信息: (More Information:)
Python Documentation on String Join
有关字符串连接的Python文档
字符串替换方法 (String Replace Method)
The str.replace(old, new, max)
method is used to replace the substring old
with the string new
for a total of max
times. This method returns a new copy of the string with the replacement. The original string str
is unchanged.
str.replace(old, new, max)
方法用于将new
字符串替换为old
子字符串,总共达到max
次。 此方法返回带有替换的字符串的新副本。 原始字符串str
保持不变。
例子 (Examples)
Replace all occurrences of
"is"
with"WAS"
将所有出现的
"is"
替换"is"
"WAS"
string = "This is nice. This is good."
newString = string.replace("is","WAS")
print(newString)
Output
输出量
ThWAS WAS nice. ThWAS WAS good.
Replace the first 2 occurrences of
"is"
with"WAS"
用
"WAS"
替换前两个出现的"is"
"WAS"
string = "This is nice. This is good."
newString = string.replace("is","WAS", 2)
print(newString)
Output
输出量
ThWAS WAS nice. This is good.
更多信息: (More Information:)
Read more about string replacement in the Python docs
在Python文档中阅读有关字符串替换的更多信息
弦剥法 (String Strip Method)
There are three options for stripping characters from a string in Python, lstrip()
, rstrip()
and strip()
.
从Python中的字符串中剥离字符有3种选择: lstrip()
, rstrip()
和strip()
。
Each will return a copy of the string with characters removed, at from the beginning, the end or both beginning and end. If no arguments are given the default is to strip whitespace characters.
每个函数都将返回字符串的副本,其中从开头,结尾或开头和结尾开始都删除了字符。 如果未提供任何参数,则默认为去除空格字符。
Example:
例:
>>> string = ' Hello, World! '
>>> strip_beginning = string.lstrip()
>>> strip_beginning
'Hello, World! '
>>> strip_end = string.rstrip()
>>> strip_end
' Hello, World!'
>>> strip_both = string.strip()
>>> strip_both
'Hello, World!'
An optional argument can be provided as a string containing all characters you wish to strip.
可以提供一个可选参数作为包含您要删除的所有字符的字符串。
>>> url = 'www.example.com/'
>>> url.strip('w./')
'example.com'
However, do notice that only the first .
got stripped from the string. This is because the strip
function only strips the argument characters that lie at the left or rightmost. Since w comes before the first .
they get stripped together, whereas ‘com’ is present in the right end before the .
after stripping /
.
但是,请注意,只有第一个.
被从弦上剥夺了。 这是因为strip
函数仅会剥离最左边或最右边的参数字符。 由于w在第一个之前.
它们被剥离在一起,而“ com”出现在右端.
剥离后/
。
字符串分割法 (String Split Method)
The split()
function is commonly used for string splitting in Python.
split()
函数通常用于Python中的字符串拆分。
split()
方法 (The split()
method)
Template: string.split(separator, maxsplit)
模板: string.split(separator, maxsplit)
separator
: The delimiter string. You split the string based on this character. For eg. it could be ” ”, ”:”, ”;” etc
separator
:定界符字符串。 您根据此字符分割了字符串。 例如。 它可能是 ” ”, ”:”, ”;” 等等
maxsplit
: The number of times to split the string based on the separator
. If not specified or -1, the string is split based on all occurrences of the separator
maxsplit
:根据separator
分割字符串的次数。 如果未指定或-1,则根据所有出现的separator
对字符串进行拆分
This method returns a list of substrings delimited by the separator
此方法返回的分隔字符串的列表separator
例子 (Examples)
Split string on space: ” ”
在空格处分割字符串:“”
string = "freeCodeCamp is fun."
print(string.split(" "))
Output:
输出:
['freeCodeCamp', 'is', 'fun.']
Split string on comma: ”,”
在逗号处分割字符串:“,”
string = "freeCodeCamp,is fun, and informative"
print(string.split(","))
Output:
输出:
['freeCodeCamp', 'is fun', ' and informative']
No separator
specified
未指定separator
符
string = "freeCodeCamp is fun and informative"
print(string.split())
Output:
输出:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Note: If no separator
is specified, then the string is stripped of all whitespace
注意:如果未指定separator
符,则将字符串中的所有空格删除
string = "freeCodeCamp is fun and informative"
print(string.split())
Output:
输出:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Split string using maxsplit
. Here we split the string on ” ” twice:
使用maxsplit
分割字符串。 在这里,我们将字符串“”分割了两次:
string = "freeCodeCamp is fun and informative"
print(string.split(" ", 2))
Output:
输出:
['freeCodeCamp', 'is', 'fun and informative']
更多信息 (More Information)
Check out the Python docs on string splitting
查看有关字符串拆分的Python文档
翻译自: https://www.freecodecamp.org/news/the-string-strip-method-in-python-explained/
相关文章:

关于命名空间namespace
虽然任意合法的PHP代码都可以包含在命名空间中,但只有以下类型的代码受命名空间的影响,它们是:类(包括抽象类和traits)、接口、函数和常量。在声明命名空间之前唯一合法的代码是用于定义源文件编码方式的 declare 语句…

一 梳理 从 HDFS 到 MR。
MapReduce 不仅仅是一个工具,更是一个框架。我们必须拿问题解决方案去适配框架的 map 和 reduce 过程很多情况下,需要关注 MapReduce 作业所需要的系统资源,尤其是集群内部网络资源的使用情况。这是MapReduce 框架在设计上的取舍,…

huffman树和huffman编码
不知道为什么,我写的代码都是又臭又长。 直接上代码: #include <iostream> #include <cstdarg> using namespace std; class Node{ public:int weight;int parent, lChildren, rChildren;Node(int weight, int parent, int lChildren, int …

react 监听组合键_投资组合中需要的5个React项目
react 监听组合键Youve put in the work and now you have a solid understanding of the React library.您已经完成工作,现在对React库有了扎实的了解。 On top of that, you have a good grasp of JavaScript and are putting its most helpful features to use …

Unity 单元测试(PLUnitTest工具)
代码测试的由来 上几个星期上面分配给我一个装备系统,我经过了几个星期的战斗写完90%的代码. 后来策划告诉我需求有一定的改动,我就随着策划的意思修改了代码. 但是测试(Xu)告诉我装备系统很多功能都用不上了. Xu: 我有300多项测试用例,现在有很多项都无法运行了. 你修改了部分…

Best Time to Buy and Sell Stock II
题目: Say you have an array for which the i th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multipl…

求给定集合的幂集
数据结构中说这个问题可以用类似8皇后的状态树解法。 把求解过程看成是一棵二叉树,空集作为root,然后遍历给定集合中的元素,左子树表示取该元素,右子树表示舍该元素。 然后,root的左右元素分别重复上述过程。 就形成…

angular 命令行项目_Angular命令行界面介绍
angular 命令行项目Angular is closely associated with its command-line interface (CLI). The CLI streamlines generation of the Angular file system. It deals with most of the configuration behind the scenes so developers can start coding. The CLI also has a l…
oracle-imp导入小错filesize设置
***********************************************声明*********************************************************************** 原创作品,出自 “深蓝的blog” 博客。欢迎转载,转载时请务必注明出处。否则追究版权法律责任。表述有错误之处…

CentOS 7 下用 firewall-cmd / iptables 实现 NAT 转发供内网服务器联网
自从用 HAProxy 对服务器做了负载均衡以后,感觉后端服务器真的没必要再配置并占用公网IP资源。 而且由于托管服务器的公网 IP 资源是固定的,想上 Keepalived 的话,需要挤出来 3 个公网 IP 使用,所以更加坚定了让负载均衡后端服务器…

八皇后的一个回溯递归解法
解法来自严蔚敏的数据结构与算法。 代码如下: #include <iostream> using namespace std; const int N 8;//皇后数 int count 0;//解法统计 int a[N][N];//储存值的数组const char *YES "■"; const char *NO "□"; //const char *Y…

即时编译和提前编译_即时编译说明
即时编译和提前编译Just-in-time compilation is a method for improving the performance of interpreted programs. During execution the program may be compiled into native code to improve its performance. It is also known as dynamic compilation.即时编译是一种提…

bzoj 2588 Spoj 10628. Count on a tree (可持久化线段树)
Spoj 10628. Count on a tree Time Limit: 12 Sec Memory Limit: 128 MBSubmit: 7669 Solved: 1894[Submit][Status][Discuss]Description 给定一棵N个节点的树,每个点有一个权值,对于M个询问(u,v,k),你需要回答u xor lastans和v这两个节点…

.Net SqlDbHelper
using System.Configuration; using System.Data.SqlClient; using System.Data;namespace ExamDAL {class SqHelper{#region 属性区// 连接字符串private static string strConn;public static string StrConn{get{return ConfigurationManager.ConnectionStrings["Exam&…

C语言的一个之前没有见过的特性
代码: #include <stdio.h>int test(){int a ({int aa 0;int bb 1;int cc 2;if(aa 0 && bb 1)printf("aa %d, bb %d\n", aa, bb);//return -2;cc;});return a; }int main(){typeof(4) a test();printf("a %d\n", a); } …

如何构建顶部导航条_如何构建导航栏
如何构建顶部导航条导航栏 (Navigation Bars) Navigation bars are a very important element to any website. They provide the main method of navigation by providing a main list of links to a user. There are many methods to creating a navigation bar. The easiest…

SPSS聚类分析:K均值聚类分析
SPSS聚类分析:K均值聚类分析 一、概念:(分析-分类-K均值聚类) 1、此过程使用可以处理大量个案的算法,根据选定的特征尝试对相对均一的个案组进行标识。不过,该算法要求您指定聚类的个数。如果知道ÿ…

[ 总结 ] nginx 负载均衡 及 缓存
操作系统:centos6.4 x64 前端使用nginx做反向代理,后端服务器为:apache php mysql 1. nginx负载均衡。 nginx编译安装(编译安装前面的文章已经写过)、apache php mysql 直接使用yum安装。 nginx端口:80…

中国剩余定理(孙子定理)的证明和c++求解
《孙子算经》里面的"物不知数"说的是这样的一个题目:一堆东西不知道具体数目,3个一数剩2个,5个一数剩3个,7个一数剩2个,问一共有多少个。 书里面给了计算过程及答案:70*2 21*3 15*2 -105*2 2…

osi七层网络层_OSI层速成课程
osi七层网络层介绍 (Introduction) Have you ever wondered how data is sent through the network from one machine to another? If yes, then the Open System Interconnected model is what you are looking for.您是否曾经想过如何通过网络将数据从一台机器发送到另一台机…

KMP算法求回溯数组的步骤
KMP算法到底是什么原理就不说了,各种资料上讲的明明白白,下面我就如何用代码来实现做一下说明和记录. KMP的核心思想就是,主串不回溯,只模式串回溯。而模式串匹配到第几位时失配,要回溯多少,由模式串本身来…
【.Net】vs2017 自带发布工具 ClickOnce发布包遇到的问题
一、遇到的问题 在安装了vs2017 社区版(Community)之后 想打包安装程序(winform) 还是想用之前的 installshield来打包 发现居然打不了,在官网查了 installshield不支持社区版(Community)&…

windows平台,开发环境变量配置
1.打开我的电脑--属性--高级--环境变量 JAVA配置环境变量变量名:JAVA_HOME 变量值:C:\Program Files\Java\jdk1.7.0 变量名:CLASSPATH 变量值:.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar; 变量名:Path 变…

如何编写可测试的代码 哈利勒的方法论
Understanding how to write testable code is one of the biggest frustrations I had when I finished school and started working at my first real-world job. 当我完成学业并开始从事第一份现实世界的工作时,了解如何编写可测试的代码是我最大的挫败之一。 T…

【Java入门提高篇】Day6 Java内部类——成员内部类
内部类是什么,简单来说,就是定义在类内部的类(一本正经的说着废话)。 一个正经的内部类是长这样的: public class Outer {class Inner{} } 这是为了演示而写的类,没有什么luan用,可以看到Inner类…

POJ 1001(高精度乘法 java的2种解法)
方法1: import java.math.BigDecimal; import java.util.Scanner; public class Main {public static void main(String[] args) {Scanner sc new Scanner(System.in);while(sc.hasNext()){String d sc.next();int z sc.nextInt();BigDecimal bd new BigDecimal(d);BigDeci…

Java编写的电梯模拟系统《结对作业》
作业代码:https://coding.net/u/liyi175/p/Dianti/git 伙伴成员:李伊 http://home.cnblogs.com/u/Yililove/ 对于这次作业,我刚开始一点思绪都没有,在老师安排了结对伙伴李伊之后,我的搭档问我,我们需要什么…

HTML属性说明
HTML elements can have attributes, which contain additional information about the element.HTML元素可以具有属性,其中包含有关该元素的其他信息。 HTML attributes generally come in name-value pairs, and always go in the opening tag of an element. Th…

css中的选择器
1.在html中引入css的方法:四种方式: a.行内式(也称内联式) 如: <h1 style"color:red;test</h1> b.内嵌式 <style type"text/css"> h1{ color:red; font-size: 10.5pt; font-family: Calibri, sans-serif; line-height: normal; widow…

javascript的call()方法与apply()方法的理解
先看一段代码 function cat() {} cat.prototype{food:fish,say:function () {console.log(I love this.food);} };var blackCat new cat(); blackCat.say(); 这时,控制台输出 I love fish若此时,有另一个对象 Dog{food:bones and shit}; dog对象没有say…