xxxxxxxxxx
my_string = "I love python."
# prints "love"
print(my_string[2:6])
# prints "love python."
print(my_string[2:])
# prints "I love python"
print(my_string[:-1])
xxxxxxxxxx
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
xxxxxxxxxx
# Select substring by slicing
x = "Michael Jackson"
sub_str = x[:7] # sub_str now contains "Michael"
# return index of substring that is found in a string
# Returns the first matching index in the string
x.find("Jack") # returns 8
xxxxxxxxxx
# Example string
text = "Hello, World!"
# Get a substring using slicing
substring = text[7:12]
print(substring) # Output: World
xxxxxxxxxx
public class Substring {
public static void main(String[] args) {
//consider this string
//here indexing starts from 0 and space is considered as char in string
String s = "Welcome to Scaler"
//1
System.out.println("The substring is: " + str.substring(11));
//2
System.out.println("The substring is: " + str.substring(0, 7));
}
}
xxxxxxxxxx
public class Substring {
public static void main(String[] args) {
String s = "Scaler is part of Interviewbit";
System.out.println(”Hey” + s.str.substring(0, 0));
}
}
In Python, substrings are a sequence of characters or character(string of length 1) within another string. We can find out if a substring belongs to a string using the find() method and in operator.
xxxxxxxxxx
learn_coding = "You can learn to code for free! Yes, for free!"
substring = "paid"
print(learn_coding.index(substring))
# output
# Traceback (most recent call last):
# File "main.py", line 4, in <module>
# print(learn_coding.index(substring))
# ValueError: substring not found