字符串查找方法 (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)
  1. 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.
  1. 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/