my_str='plus2net'
print(my_str[0:]) # plus2net ( full string)
print(my_str[1:3])# lu ( from 1 to before 3)
print(my_str[-1]) # t ( last char )
print(my_str[-3:])# net ( last three char)
print(my_str[int(len(my_str)/2)]) #2 ( middle char )
my_list=['aecde','adba','acbd','abcd','abded','bdbd','baba']
search_str='ab'
filtered = [s for s in my_list if search_str in s]
Using regular expression
We can return matching strings by using search() method of regular expression. We can also use match when we want matching string from starting of the string only ( Not any where match )
import re # regular expression library
my_list=['aecde','adba','acbd','abcd','abded','bdbd','baba']
search_str='ab' # searh string
for element in my_list:
#if(re.search(search_str,element,re.IGNORECASE)):
if(re.match(search_str,element,re.IGNORECASE)):
print(element)
Output using match()
abcd
abded
If we use search() by commenting the match() method and using the search() , output is here
abcd
abded
baba
String between two sub-strings
Here is a variable declared in PHP, we have to collect the value of the variable.
$var1=PY_tkinter_end;
Our ouput should collect the value assigned i.e tkinter
import re
data="$var1=PY_tkinter_end;"
str1 = re.search('PY_(.*)_end', data)
print(str1.group(1)) # tkinter
Here is the original string with escape chars to take care the double quotes. Out final output should read Data within Description
<META NAME=\"DESCRIPTION\" CONTENT=\"Data within Description\">
des = re.search('<META NAME=\\\\"DESCRIPTION\\\\" CONTENT=\\\\"(.*)\\\\">', data)