📜  Python|使用列表切片从给定字符串中获取子字符串

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

Python|使用列表切片从给定字符串中获取子字符串

给定一个字符串,编写一个Python程序,使用列表切片从给定字符串中获取子字符串。让我们尝试使用不同的示例来实现这一点。

代码#1:

在此示例中,我们将看到如何从字符串的末尾或开头获取子字符串。

# Python3 code to demonstrate
# to create a substring from a string
  
# Initialising string
ini_string = 'xbzefdgstb'
  
# printing initial string and character
print ("initial_strings : ", ini_string)
  
# creating substring from start of string
# define length upto which substring required
sstring_strt = ini_string[:2]
sstring_end = ini_string[3:]
  
# printing result
print ("print resultant substring from start", sstring_strt)
print ("print resultant substring from end", sstring_end)
输出:
initial_strings :  xbzefdgstb
print resultant substring from start xb
print resultant substring from end efdgstb


代码#2:

在此示例中,我们将看到如何通过从特定位置间隙中获取字符来创建字符串。

# Python3 code to demonstrate
# to create a substring from string
  
# Initialising string
ini_string = 'xbzefdgstb'
  
# printing initial string and character
print ("initial_strings : ", ini_string)
  
# creating substring by taking element
# after certain position gap
# define length upto which substring required
sstring_alt = ini_string[::2]
sstring_gap2 = ini_string[::3]
  
# printing result
print ("print resultant substring from start", sstring_alt)
print ("print resultant substring from end", sstring_gap2)
输出:
initial_strings :  xbzefdgstb
print resultant substring from start xzfgt
print resultant substring from end xegb


代码#3:

在此示例中,我们正在考虑从中间获取字符串的两种情况,其中字符之间存在一些位置间隙。

# Python3 code to demonstrate
# to create a substring from string
  
# Initialising string
ini_string = 'xbzefdgstb'
  
# printing initial string and character
print ("initial_strings : ", ini_string)
  
# creating substring by taking element
# after certain position gap
# in defined length
sstring = ini_string[2:7:2]
  
# printing result
print ("print resultant substring", sstring)
输出:
initial_strings :  xbzefdgstb
print resultant substring zfg