📜  Python – 字符串直到子字符串

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

Python – 字符串直到子字符串

有时,除了查找子字符串之外,我们可能还需要获取在找到子字符串之前出现的字符串。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 partition()

分区函数可用于执行此任务,其中我们只返回出现在分区词之前的分区部分。

Python3
# Python3 code to demonstrate
# String till Substring
# using partition()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing split word
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
# printing split string
print("The split string : " + str(spl_word))
 
# using partition()
# String till Substring
res = test_string.partition(spl_word)[0]
 
# print result
print("String before the substring occurrence : " + res)


Python3
# Python3 code to demonstrate
# String till Substring
# using split()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing split word
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
# printing split string
print("The split string : " + str(spl_word))
 
# using split()
# String till Substring
res = test_string.split(spl_word)[0]
 
# print result
print("String before the substring occurrence : " + res)


输出 :
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is


方法 #2:使用 split()

split函数也可以用来执行这个特定的任务,在这个函数中,我们使用限制拆分的力量,然后打印前一个字符串。

Python3

# Python3 code to demonstrate
# String till Substring
# using split()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing split word
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
# printing split string
print("The split string : " + str(spl_word))
 
# using split()
# String till Substring
res = test_string.split(spl_word)[0]
 
# print result
print("String before the substring occurrence : " + res)
输出 :
The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is