substring in python code example
Example 1: python substring
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
Example 2: python extract substring
# string [start:end:step]
string = "freeCodeCamp"
print(string[0:len(string)-1]) # freeCodeCam
print(string[0:5]) # freeC
print(string[2:6]) # eeCo
print(string[-1]) # p
print(string[-5:]) # eCamp
print(string[1:-4]) # reeCode
print(string[-5:-2]) # eCa
print(string[::2]) # feCdCm
Example 3: find a substring in a string java
package hello;
public class SubStringProblem {
public static void main(String[] args) {
System.out
.println("Checking if one String contains another String using indexOf() in Java");
String input = "Java is the best programming language";
boolean isPresent = input.indexOf("Java") != -1 ? true : false;
if (isPresent) {
System.out.println("input string: " + input);
System.out.println("search string: " + "Java");
System.out.println("does String contains substring? " + "YES");
}
System.out.println("Doing search with different case");
isPresent = input.indexOf("java") != -1 ? true : false;
System.out.println("isPresent: " + isPresent);
System.out
.println("Checking if one String contains another String using contains() in Java");
input = "C++ is predecessor of Java";
boolean isFound = input.contains("Java");
if (isFound) {
System.out.println("input string: " + input);
System.out.println("search string: " + "Java");
System.out.println("does substring is found inside String? " + "YES");
}
System.out.println("Searching with different case");
isFound = input.contains("java");
System.out.println("isFound: " + isFound);
}
}
Output
Checking if one String contains another String using indexOf() in Java
input string: Java is the best programming language
search string: Java
does String contain substring? YES
Doing search with different case
isPresent: false
Checking if one String contains another String using contains() in Java
input string: C++ is the predecessor of Java
search string: Java
does substring is found inside String? YES
Searching for different case
isFound: false
Example 4: python substring from string
string[start: end: step]
Example 5: count substring in string python
def count_substring(string,sub_string):
l=len(sub_string)
count=0
for i in range(len(string)-len(sub_string)+1):
if(string[i:i+len(sub_string)] == sub_string ):
count+=1
return count