Home > Article > Backend Development > How to delete everything before or after a specified character in Python
my_str = 'fql!jiyik!com' separator = '!' result = my_str.split(separator, 1)[0] print(result) # ????️ 'fql'
We use the str.split() method to remove everything after the character (! in the example).
str.split() method splits a string into a list of substrings using delimiters.
This method takes the following 2 parameters:
separator splits the string into substrings every time a separator appears
maxsplit Complete at most maxsplit splits (optional)
If the delimiter is not found in the string, a list containing only 1 element is returned.
We set the maxsplit parameter to 1 because we only need to split the string once.
This example deletes everything after the first occurrence of the character in the string.
my_str = 'fql!jiyik!com' separator = '!' result_1 = my_str.split(separator, 1)[0] print(result_1) # ????️ 'fql' # ????️ ['fql', 'jiyik!com'] print(my_str.split(separator, 1))
Please note that the delimiter is not included in the string. If you need to include it, use the addition ( ) operator.
my_str = 'fql!jiyik!com' # ✅ 删除字符后的所有内容,保留分隔符 separator = '!' result = my_str.split(separator, 1)[0] + separator print(result) # ????️ fql!
The addition operator can be used to concatenate strings in Python.
If we need to delete everything after the last occurrence of the character in the string, use the str.rsplit() method.
my_str = 'fql!jiyik!com' separator = '!' # ✅ 删除字符最后一次出现后的所有内容 result = my_str.rsplit(separator, 1)[0] print(result) # ????️ 'fql!jiyik'
rsplit() behaves like split() except that it splits from the right side.
str.rsplit() method splits the string from the right, when maxsplit is set to 1, it only splits once.
If we need to include the character you split on, use the addition operator ( ).
my_str = 'fql!jiyik!com' separator = '!' result = my_str.rsplit(separator, 1)[0] + separator print(result) # ????️ 'fql!jiyik!'
We can also use the str.partition() method to delete everything after a specific character in the string.
my_str = 'fql!jiyik!com' separator = '!' result = my_str.partition(separator)[0] print(result) # ????️ 'fql' result = ''.join(my_str.partition(separator)[0:2]) print(result) # ????️ 'fql!'
The str.partition method splits a string on the first occurrence of the provided delimiter.
This method returns a tuple containing 3 elements - the part before the delimiter, the part after the delimiter and the part after the delimiter.
my_str = 'fql!jiyik!com' separator = '!' # ????️ ('fql', '!', 'jiyik!com') print(my_str.partition(separator))
If the delimiter is not found in the string, this method returns a tuple containing the string, followed by 2 empty strings.
If we need to include a delimiter in the result, use the str.join() method to join the first and second list items.
my_str = 'fql!jiyik!com' separator = '!' result = ''.join(my_str.partition(separator)[0:2]) print(result) # ????️ 'fql!'
The str.join method takes an iterable object as a parameter and returns a string that is the concatenation of the strings in the iterable object.
The string on which this method is called is used as a separator between elements.
To delete everything before a character in a string:
Use The str.find() method gets the index of a character.
Use string slicing and set the starting index to the index of the character.
The new string will not contain the previous characters.
my_str = 'apple, banana' result = my_str[my_str.find('b'):] print(result) # ????️ banana
The str.find method returns the index of the first occurrence of the provided substring in a string.
We use string slicing to get a part of the original string that starts at the index of the character and continues to the end of the string.
Please note that the str.find() method returns -1 if the substring is not found in the string.
We can handle the situation where the find() method returns -1 in the if/else statement.
my_str = 'apple, banana' index = my_str.find('b') print(index) # ????️ 7 if index != -1: result = my_str[index:] else: result = my_str # ????️ alternatively raise an error print(result) # ????️ 'banana'
This is an example of a case where the supplied character is not in the string.
my_str = 'apple, banana' index = my_str.find('z') print(index) # ????️ -1 if index != -1: result = my_str[index:] else: result = my_str # ????️ alternatively raise an error print(result) # ????️ 'apple, banana'
Our else statement assigns the result variable to the entire string, however, an exception can be thrown.
my_str = 'apple, banana' index = my_str.find('z') print(index) # ????️ -1 if index != -1: result = my_str[index:] else: # ????️ this runs raise IndexError('provided character not in string')
If we need to delete everything before the last occurrence of the character, use the str.rfind() method.
my_str = 'apple,banana,bear' result = my_str[my_str.rfind('b'):] print(result) # ????️ 'bear'
str.rfind method returns the highest index in the string at which the supplied substring is found.
If the string does not contain a substring, this method returns -1.
We can use if/else statements to handle situations where characters do not exist in the string.
my_str = 'apple,banana,bear' index = my_str.rfind('b') if index != -1: result = my_str[index:] else: result = my_str print(result) # ????️ 'bear'
If the else block runs, we set the result variable to the entire string.
Alternatively, we can raise the error in the else block, such as raise IndexError('your message here').
We can also use the str.rsplit() method to delete everything before the last occurrence of the character.
To delete everything before the last occurrence of a character:
Use The str.rsplit() method splits the string from the right.
Access the list item at index 1.
The result will be a string containing everything after the last occurrence of that character.
my_str = 'example.com/articles/python' result = my_str.rsplit('/', 1)[1] print(result) # ????️ 'python' # ????️ 如果你想在结果中包含这个字符 result_2 = '/' + my_str.rsplit('/', 1)[1] print(result_2) # ????️ '/python' # ????️ ['example.com/articles', 'python'] print(my_str.rsplit('/', 1))
We use the str.rsplit() method to delete everything before the last character appears.
str.rsplit method returns a list of words in a string using the provided delimiter as the delimiter string.
my_str = 'one two three' print(my_str.rsplit(' ')) # ????️ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # ????️ ['one two', 'three']
This method takes the following 2 parameters:
separator splits the string into substrings every time a separator occurs
maxsplit does maxsplit splitting at most, the rightmost (optional)
rsplit() behaves like split() except splitting from the right .
请注意 ,我们为 maxsplit 参数提供了值 1,因为我们只想从右侧拆分字符串一次。
my_str = 'example.com/articles/python' result = my_str.rsplit('/', 1)[1] print(result) # ????️ 'python' # ????️ ['example.com/articles', 'python'] print(my_str.rsplit('/', 1))
最后一步是访问索引 1 处的列表元素,以获取包含指定字符最后一次出现之后的所有内容的字符串。
如果要在结果中包含该字符,请使用加法 + 运算符。
my_str = 'example.com/articles/python' result = '/' + my_str.rsplit('/', 1)[1] print(result) # ????️ '/python'
或者,我们可以使用 str.rpartition() 方法。
my_str = 'example.com/articles/python' result = my_str.rpartition('/')[2] print(result) # ????️ 'python' # ????️ ('example.com/articles', '/', 'python') print(my_str.rpartition('/'))
str.rpartition 方法在提供的分隔符的最后一次出现处拆分字符串。
该方法返回一个包含 3 个元素的元组 - 分隔符之前的部分、分隔符和分隔符之后的部分。
如果在字符串中找不到分隔符,则该方法返回一个包含两个空字符串的元组,后跟字符串本身。
如果需要在结果中包含分隔符,请使用 str.join() 方法连接第二个和第三个列表项。
my_str = 'example.com/articles/python' result = ''.join(my_str.rpartition('/')[1:]) print(result) # ????️ '/python'
str.join 方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。
调用该方法的字符串用作元素之间的分隔符。
The above is the detailed content of How to delete everything before or after a specified character in Python. For more information, please follow other related articles on the PHP Chinese website!