Python 子字符串

在 Python 编程语言中,我们没有专门的字符串函数来查找或返回子字符串。但是,我们有多种选项可以从此语言中提取或返回子字符串。

在本节中,我们将解释所有可能的选项以及示例,用于返回子字符串。我们使用一些内置函数和功能来获取或查找 Python 中的字符串子字符串。

Python 子字符串示例

以下是提取或返回子字符串的示例列表。

选项 #1:字符串切片

在此编程语言中,您可以对任何对象进行切片以返回对象的一部分。在此示例中,我们使用切片概念来返回 Python 子字符串。切片接受三个参数,分别是开始点、停止点和步长。

s1 = 'Tutorial Gateway'
 
print(s1[:]) # returns complete characters
 
print(s1[: 5]) # From 0 to 5
 
print(s1[1 : 10])
 
print(s1[2 : 13])
 
print(s1[5 : 15]) # from 5 to 15

切片输出

Tutorial Gateway
Tutor
utorial G
torial Gate
ial Gatewa

Python 切片也接受负数来获取子字符串。在此示例中,我们使用负索引作为终点。负索引意味着它从最右边的字符序列计数到左边。这意味着 print(s2[2 : -13]) 返回从 2 到结束 -13 的子字符串(删除最右边的 13 个字符)。

s2 = 'Learning this Program'
 
print(s2[:])
 
print(s2[: -5]) #  from 0
 
print(s2[1 : -10])
 
print(s2[2 : -13])
 
print(s2[4 : -1])
 
print(s2[3 : -4])
Learning this Program
Learning this Pr
earning th
arning
ning this Progra
rning this Pro

在此示例中,我们使用切片中的第三个值。它可以帮助您跳过字符。例如,[0: 14: 2] 返回从 0 到 14 的 Python 子字符串,其中它会跳过交替的字符(每隔 1 个字符)。我建议您参考 Python 中的 字符串函数

wrd = 'English Programming Language for Free'
 
print(wrd[:])
 
print(wrd[0 : 14]) # is equal to print([0 : 14 : 1])
 
print(wrd[0 : 14 : 2]) 
 
print(wrd[0 : 14 : 3]) # skips every third character
 
print(wrd[2 : 30 : 2])
 
print(wrd[1 : 25 : 3])
Python String substring Function Example

选项 #2:使用切片定义函数

与其每次都对对象进行切片,不如创建一个 Python 函数来对字符串进行切片并返回子字符串。通过这种方式,您可以允许用户像使用任何内置函数一样使用此函数。

在此示例中,我们定义了一个接受字符串、起始点和结束点的函数。接下来,它将第一个参数从起始点切片到结束点并返回结果。请参考 Python 中的 函数函数类型 来了解函数创建和类型。

def sbs(s3, start, end):
    return s3[start:end]
 
s3 = 'Coding Examples'
 
print(sbs(s3, 1, 5))
 
print(sbs(s3, 2, 10))
 
print(sbs(s3, 3, 14))
odin
ding Exa
ing Example

我们在子字符串示例中使用起始点和长度。此函数接受一个字符串和可选参数起始点和长度。

def substr(st, start = None, length = None):
    return st[start : ][: length]
 
st = 'Learning this Programming Language'
 
print(substr(st))
 
print(substr(st, 3))
 
print(substr(st, 2, 19))
 
print(substr(st, length = 10))
Learning this Programming Language
rning this Programming Language
arning this Program
Learning t

这比上面的示例更好。

def sbstr(st1, start = None, length = None):
    return st1[start : length]
 
st1 = 'Learn this Programming Language'
 
print(sbstr(st1))
 
print(sbstr(st1, 7))
 
print(sbstr(st1, 2, 19))
 
print(sbstr(st1, length = 15))
Learn this Programming Language
his Programming Language
arn this Programm
Learn this Prog

在此示例中,我们使用另一个称为步长的参数来跳过字符。

def strsub(st2, start, end, steps = 1):
    return st2[start : end : steps]
 
st2 = 'Learn Tableau PowerBI and SSIS  for Free'

print(strsub(st2, 1, 5))
print(strsub(st2, 1, 5, 2))
 
print(strsub(st2, 2, 30))
print(strsub(st2, 2, 30, 3))
 
print(strsub(st2, 0, 35, 3))
print(strsub(st2, 0, 35, 4))
earn
er
arn Tableau PowerBI and SSIS
a baPeInSS
LrTluor dS o
LnbuwIdIf

选项 #3:反向子字符串

通过使用负值,您还可以以反向顺序返回子字符串。

str1 = 'Learn this Simple Programming Language'
 
print(str1[:: -1])
 
print(str1[19:: -1])
 
print(str1[4 :: -1])
 
print(str1[9 :: -1])
 
print(str1[11 :: -1])
egaugnaL gnimmargorP elpmiS siht nraeL
rP elpmiS siht nraeL
nraeL
siht nraeL
S siht nraeL

选项 #4:使用 For 循环

您还可以使用 for 循环range 函数 来返回它。为此,我们必须使用 print 函数 和 end 参数。此示例返回一个从 3 开始到 24 结束的句子。

str2 = 'Pycharm Programming Language for Free'
 
for n in range(3, 25):
    print(str2[n], end = '')
harm Programming Langua

选项 #5:使用 slice 函数的 Python 子字符串

slice 函数允许您对给定的字符串进行切片并返回子字符串。此函数接受起始点和结束点。通过使用这些值,您可以从任何给定的起始点到结束点返回句子。例如,slice(3, 13) 返回从索引为 4 的字符到索引为 13 的字符的句子。

str3 = 'Learn English Language for Free'
 
sub1 = slice(4)
print(str3[sub1])
 
sub2 = slice(3, 13)
print(str3[sub2])
 
sub3 = slice(1, 21)
print(str3[sub3])
 
sub4 = slice(1, 28)
print(str3[sub4])
 
sub5 = slice(7, 29)
print(str3[sub5])
Lear
rn English
earn English Languag
earn English Language for F
nglish Language for Fr

在这里,我们使用负值从右到左切片。接下来,我们使用 -1 作为第三个参数以反向顺序返回子字符串。

str4 = 'Learn English Language for Free'
 
sub1 = slice(-1, -7, -1)
print(str4[sub1])
 
sub2 = slice(-7, 3, -1)
print(str4[sub2])
eerF r
of egaugnaL hsilgnE n

选项 #6:子字符串匹配

使用 If Else 和 not In 运算符检查单词是否在给定的字符串中。

a = 'Hello World'
 
substr = 'Hello'
 
if substr not in a:
    print('We haven\'t found what you are looking for = ', substr)
else:
    print('We found the Matching = ', substr)
We found the Matching = Hello

这次,我们使用 if in 运算符来检查不存在的单词。

b = 'We are abc working at abc company'
 
word = 'xyz'
 
if word in b:
    print('We found the Matching = ', word)
else:
    print('We haven\'t found what you are looking for = ', word)
We haven't found what you are looking for =  xyz

not in 运算符不是检查匹配的唯一方法。您可以使用 find 函数

str5 = 'We are abc working at abc company'
 
subst = 'abc'
 
if str5.find(subst) == -1:
    print('We haven\'t found what you are looking for = ', subst)
else:
    print('We found the Matching = ', subst)
We found the Matching = abc

选项 #7:用于字符前子字符串的 Python split 函数

此示例演示了如何返回字符前的文本。为此,我们正在使用名为 Split 的内置函数。

在这里,我们使用 split 函数将给定的文本按空格分割成两个子字符串,并将这些分割后的字符串分配给两个变量。

c = 'Tutorial Gateway'
 
first, second = c.split(' ')
 
print('Before Character space = ', first)
Before Character space = Tutorial

在此示例中,我们使用此 split 函数来返回字符之前和之后的句子。

time = '22:30:55'
 
hour, minute, second = time.split(':')
 
print('Before First Character : = ', hour)
print('Before Second Character : = ', minute)
print('After Second Character : = ', second)
 
print('------------')
first, second = time.split(':', 1)
print('Before First Character : = ', first)
print('After First Character : = ', second)
 
print('------------')
first, second = time.rsplit(':', 1)
print('Before Second Character : = ', first)
print('After Second Character : = ', second)
Before First Character : =  22
Before Second Character : =  30
After Second Character : =  55
------------
Before First Character : =  22
After First Character : =  30:55
------------
Before Second Character : =  22:30
After Second Character : =  55

字符后

此示例演示了如何返回字符后的子字符串。

d = 'Hello World!'
 
first, second = d.split(' ')
 
print('Before the Space = ', first)
print('After the Space = ', second)
Before the Space =  Hello
After the Space =  World!

有时,您可能需要将 @ 符号之前的句子和域名作为单独的字符串返回。在这种情况下,您可以使用 split 函数将字符串分割成两个句子。

e = 'contact@tutorialgateway.org'
 
name, domain = e.split('@')
 
print('Before Character @ = ', name)
print('After Character @ = ', domain)
Before Character @ =  contact
After Character @ =  tutorialgateway.org

选项 #8:使用 index 函数的 Python 子字符串

index 函数用于查找给定字符的索引位置。在此示例中,我们使用此函数来查找子字符串的索引。接下来,我们从起始点 (0) 到该索引点切片对象——有点像开始于该索引位置的字符之前的文本。

f = 'We are abc group working at abc company as a abc Developer';
 
end1 = f.index('bc') 
print(f[: end1])
 
end2 = f.index('group') 
print(f[: end2])
 
end3 = f.index('abc') 
print(f[: end3])
 
end4 = f.index('abc', 11) 
print(f[: end4])
 
end5 = f.index('abc', 35) 
print(f[: end5])
We are a
We are abc 
We are 
We are abc group working at 
We are abc group working at abc company as a 

在这里,我们使用半个字符串的索引位置作为起始位置。例如,字符索引位置之后的子字符串。

g = 'We are xyz group working at xyz company as a xyz Developer';
 
start1 = g.index('at') 
print(g[start1 : ])
print(g[0 : start1])
 
start2 = g.index('working') 
print(g[start2 : ])
 
start3 = g.index('xyz') 
print(g[start3 :])
 
start4 = g.index('xyz', 11) 
print(g[start4 :])
 
start5 = g.index('xyz', 35) 
print(g[start5 : ])
at xyz company as a xyz Developer
We are xyz group working 
working at xyz company as a xyz Developer
xyz group working at xyz company as a xyz Developer
xyz company as a xyz Developer
xyz Developer

选项 #9:使用 find 方法的子字符串

您可以使用 find 函数 来匹配或查找字符串中的字符。接下来,您可以使用此 Python 字符串切片在字符之前或之后返回文本。在此示例中,我们查找空格并返回其之前和之后的文本。

h = 'Coding Examples'
 
index_num = h.find(' ')
 
print('Before the Space = ', h[ : index_num])
print('After the Space = ', h[index_num : ])
Before the Space =  Coding
After the Space =   Examples

在这里,我们使用第二个参数(起始点)来查找句子。接下来,我们返回该字符之前和之后子字符串。

i = 'We are abc group working as a abc Developer in abc company';
 
end1 = i.find('group') 
print('Before: ', i[: end1])
print('After: ', i[end1 : ])
 
end2 = i.find('abc') 
print('\nBefore: ', i[: end2])
print('After: ', i[end2 : ])
 
end3 = i.find('abc', 11) 
print('\nBefore: ', i[: end3])
print('After: ', i[end3 : ])
 
end4 = i.find('abc', 35) 
print('\nBefore: ', i[: end4])
print('After: ', i[end4 : ])
Before:  We are abc 
After:  group working as a abc Developer in abc company

Before:  We are 
After:  abc group working as a abc Developer in abc company

Before:  We are abc group working as a 
After:  abc Developer in abc company

Before:  We are abc group working as a abc Developer in 
After:  abc company

让我们看看如何在字符串中计算单词的出现次数。为此,我们使用 count 函数

j = 'we are abc group working as a abc developer in abc company';
 
print('Number of Times "a" Occurred : ', j.count('a'))
print('Number of Times "o" Occurred : ', j.count('o'))
print('Number of Times "abc" Occurred : ', j.count('abc'))
Number of Times "a" Occurred :  7
Number of Times "o" Occurred :  4
Number of Times "abc" Occurred :  3