📜  Python – 在字符串中的子字符串之后删除

📅  最后修改于: 2022-05-13 01:54:45.073000             🧑  作者: Mango

Python – 在字符串中的子字符串之后删除

给定一个字符串,删除特定子字符串之后的所有字符。

方法 #1:使用 index() + len() + 切片

在此,我们首先获取要执行删除的子字符串的索引,然后使用 len() 将其长度添加到该索引上,然后使用切片将该字符串之后的元素切片。

Python3
# Python3 code to demonstrate working of 
# Remove after substring in String
# Using index() + len() + slicing
  
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing sub string 
sub_str = "best"
  
# slicing off after length computation
res = test_str[:test_str.index(sub_str) + len(sub_str)]
  
# printing result 
print("The string after removal : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove after substring in String
# Using regex() ( for stripping off after numeric occurrence)
import re
  
# initializing strings
test_str = 'geeksforgeeks is best 4 geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# slicing after the numeric occurrence
res = re.match(r"(.*\d+)", test_str).group()
  
# printing result 
print("The string after removal : " + str(res))


输出
The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

方法 #2:使用 regex() (用于在出现数字后剥离)

这是对稍微不同的问题的解决方案,在该问题中,出现数字后需要删除字符串。我们采用匹配操作,并在找到匹配之前保留所有内容。

Python3

# Python3 code to demonstrate working of 
# Remove after substring in String
# Using regex() ( for stripping off after numeric occurrence)
import re
  
# initializing strings
test_str = 'geeksforgeeks is best 4 geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# slicing after the numeric occurrence
res = re.match(r"(.*\d+)", test_str).group()
  
# printing result 
print("The string after removal : " + str(res)) 
输出
The original string is : geeksforgeeks is best 4 geeks
The string after removal : geeksforgeeks is best 4