Python slice() function
In this article, we will learn about the Python slice() function/method with the help of multiple examples.Example
String = 'Hello World'slice_obj = slice(5,11)print(String[slice_obj]) |
Output:
World
A sequence of objects of any type (string, bytes, tuple, list, or range) or the object which implements __getitem__() and __len__() functions/method then this object can be sliced using slice() method.
Python slice() Function Syntax
Syntax: slice(start, stop, step)
Parameters:
- start: Starting index where the slicing of object starts.
- stop: Ending index where the slicing of object stops.
- step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.
Note: If just one parameter is passed, then the start and step are considered to be None.
slice() Function in Python Examples
Python slice string
We have created the string CodeConfig, and we are using the slice function/method to slice the string. The first slice function/method is slicing the string to the 2nd index, the second slice function/method is have used to slice the string to the 4th index with a leaving 2nd index. Finally, we are printing both sliced strings in the terminal.
# String slicingString = 'CodeConfig'slice_obj1 = slice(3)slice_obj2 = slice(1, 5, 2)print("String slicing")print(String[slice_obj1])print(String[slice_obj2]) |
Output:
String slicing Cod eC
Python slice list or Python slice array
We have created the list [1,2,3,4,5], and we are using the slice function/method to slice the list. The first slice function/method is slicing the list to the 2nd index, the second slice function/method is have used to slice the list to the 4th index with a leaving 2nd index. Finally, we are printing both sliced lists in the terminal.
L = [1, 2, 3, 4, 5]slice_obj1 = slice(3)slice_obj2 = slice(1, 5, 2)print("List slicing")print(L[slice_obj1])print(L[slice_obj2]) |
Output:
List slicing [1, 2, 3] [2, 4]
Python slice tuple
We have created a tuple of 5 numbers, and we are using the slice function/method 2 times, first slice function/method is slicing the tuple to 2 indexes, and the second slice function/method is slicing the tuple to 4 indexes and every second element is sliced.
# Tuple slicingT = (1, 2, 3, 4, 5)slice_obj1 = slice(3)slice_obj2 = slice(1, 5, 2)print("Tuple slicing")print(T[slice_obj1])print(T[slice_obj2]) |
Output:
Tuple slicing (1, 2, 3) (2, 4)
Negative indexing
In Python, negative sequence indexes represent positions from the end of the array. slice() function/method can also have negative values. In that case, the iteration will be performed backwards i.e. from end to start.
Get a sub-list using a negative index with a slice()
In the example. We have created a list with values ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’. We are slicing the string from the 2nd index from the last and going to the 6th index from the last, with the hop of -1.
l = ['a', 'b', 'c', 'd', 'e', 'f']slice_obj = slice(-2, -6, -1)print("list slicing:", l[slice_obj]) |
Output:
list slicing: ['e', 'd', 'c', 'b']
Get a sub-string using a negative index with a slice()
We have created a string of letters, we are using the slice function/method with a negative index of -1 to slice the string apart from the last letter.
s = "Codes"slice_obj = slice(-1)print("string slicing:", s[slice_obj]) |
Output:
string slicing: Code
Get a sub-tuple using a negative index with slice()
In the code, slice_obj = slice(-1, -3, -1) creates a slice object that will slice the tuple starting from the second-to-last element (index -1), up to (but not including) the fourth-to-last element (index -3), with a step size of -1. This means that the sliced tuple will contain the elements [9, 7], in reverse order.
t = (1, 3, 5, 7, 9)slice_obj = slice(-1, -3, -1)print("tuple slicing:", t[slice_obj]) |
Output:
tuple slicing: (9, 7)
Using Indexing Syntax for Slicing with String
In the example, we have created a list named slice_str with the value ‘CodesForCodes‘.The first slice is printing the value till the 4 indexes and the second slice is printing till the 5th index with a hop of every 2nd index.
slice_str = 'CodesForCodes'print(slice_str[0:5]) print(slice_str[1:6:2]) |
Output:
Codes esF
Using Indexing Syntax for Slicing with List
In the example, we have created a list named slice_list and we have inserted [‘C’,’o’,’d’,’e’,’s’,’F’,’o’,’r’,’C’,’o’,’d’,’e’,’s’] these values to our list. The first slice is printing the value till 4 indexes and the second slice is printing till the 5th index with a hop of every 2nd index.
slice_list = ['C','o','d','e','s','F','o','r','C','o','d','e','s']print(slice_list[0:5]) print(slice_list[1:6:2]) |
Output:
['C', 'o', 'd', 'e', 's'] ['e', 's', 'F']
Slicing and modifying a list
In the example, we have created a list of numbers named slice_numbers which consists of 5 variables [1,2,3,4,5] in it.Then we are slicing the list from index 1 to 3 and also modify its value from [1,2,3] to [10,20,30] and finally, we are printing the slice_numbers list.
slice_numbers = [1, 2, 3, 4, 5]print("slice_number before slicing and modfication : ",end=' ')print(slice_numbers) slice_numbers[1:4] = [10, 20, 30]print("slice_number after slicing and modfication : ",end=' ')print(slice_numbers) |
Output:
slice_number before slicing and modfication : [1, 2, 3, 4, 5] slice_number after slicing and modfication : [1, 10, 20, 30, 5]
Python string strip
Python String strip() Method
strip() method removes all leading and trailing whitespace characters from a string in Python. We can also customize it to strip specific characters by passing a string of characters to remove. It doesn’t modify the original string but returns a new one.
Let’s take an example to remove whitespace from both ends of a string.
s = " CodeConfig.in "
res = s.strip()
print(res)
Output
CodeConfig.in
Explanation:
- The functions/method removes spaces at the start and end of the string.
- Inner spaces are not affected. This is useful for cleaning up user inputs or formatted text.
Table of Content
Syntax of strip() Method
s.strip(chars)
Parameters:
- chars(optional)A string specifying the set of characters to remove from the beginning and end of the string.
- If omitted,
strip()removes all leading and trailing whitespace by default.
Return Type:
- String: A new string with the specified characters (or whitespace) removed from both ends is returned.
Examples of strip() Method
Removing Custom Characters
We can also use custom characters from the beginning and end of a string. This is useful when we may be interested to clean up specific unwanted characters such when symbols, punctuation, or any other characters that are not part of the core string content
s = ' ##*#CodeConfig#**## '
# removes all occurrences of '#', '*', and ' '
# from start and end of the string
res = s.strip('#* ')
print(res)
Output
CodeConfig
Explanation:
- strip(‘#* ‘) removes any #, *, and spaces from both beginning and end of the string.
- It stops stripping characters from both end once it encounters a character that are not in the specified set of characters.
Removing Newline Characters
We can also remove the leading and trailing newline characters (\n) from a string.
s = '\nCodes for Codes\n'
# Removing newline characters from both ends
res = s.strip()
print(res)
Output
Codes for Codes
Frequently Asked Questions (FAQs) enabled Python strip() Method
What characters does strip() remove by default?
By default, strip() removes whitespace characters, including spaces, tabs (\t), and newlines (\n).
Can strip() remove characters from the middle of a string?
No, strip() just removes characters from the beginning and end of a string. Characters in the middle of the string remain unaffected.
How is strip() distinct from replace()?
The strip() functions/method is have used for trimming characters from the ends of a string, when replace() can replace occurrences of a character or substring anywhere in the string.
Python string replace
Python String replace() Method
The replace() functions/method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.
Let's look at a simple example of replace() method.
s = "Hello World! Hello Python!"
# Replace "Hello" with "Hi"
s1 = s.replace("Hello", "Hi")
print(s1)
Output
Hi World! Hi Python!
Explanation: Here, “Hello” is replaced by “Hi” throughout the string, resulting in “Hi World! Hi Python!“.
Note: Since replace() creates a new string, the original string remains unchanged.
Table of Content
Syntax of String replace() Method
string.replace(old, new, count)
Parameters
- old: The substring we may be interested to replace.
- new: The new substring that we may be interested to replace with old substring.
- count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.
Return Type
- Returns a new string with the specified replacements made. The original string remains unchanged since strings in Python are immutable.
Using replace() with Count Limit
By using the optional count parameter, we can limit the number of replacements made. This can be helpful when just a specific number of replacements are desired.
s = "apple apple apple"
# Replace "apple" with "orange" just once
s1 = s.replace("apple", "orange", 1)
print(s1)
Output
orange apple apple
Explanation: replace() method just replaces the first instance of “apple” because we specified count=1.
Case Sensitivity in replace()
The replace() functions/method is case-sensitive, it treats uppercase and lowercase characters when distinct. If we may be interested to replace both cases then we have to use additional logic.
s = "Hello, World! hello, world!"
# Replace just lowercase 'hello'
s1 = s.replace("hello", "hi")
print(s1)
# Replace just uppercase 'Hello'
s2 = s.replace("Hello", "Hi")
print(s2)
Output: text in bold will get updated
Hello, World! hi, world! Hi, World! hello, world!
Python replace all occurrences of a substring in a string
Sometimes, when working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other.
Input : test_str = “CodesForCodes” s1 = “Codes” s2 = “Test”
Output : test_str = “TestforTest” Explanation: We replace all occurrences of s1 with s2 in test_str.Input : test_str = “CodeConfigCode” s1 = “for” s2 = “ABC”
Output : test_str = “ABCConfigABC”
Method 1
We can use inbuilt function/method replace present in python3 to replace all occurrences of substring.
Implementation using the inbuilt function: -
#Python has inbuilt function/method replace to replace all occurrences of substring.input_string = "CodeConfigCode"s1 = "Code"s2 = "abcd"input_string = input_string.replace(s1, s2)print(input_string) |
abcdCofigabcd
Method 2:
Splitting the string by substring and then replacing with the new string.split() function/method is used.
#code for replacing all occurrences of substring s1 with new string s2test_str="CodeConfigCode"s1="Code"s2="abcd"#string split by substrings=test_str.split(s1)new_str=""for i in s: if(i==""): new_str+=s2 else: new_str+=i#printing the replaced stringprint(new_str) |
abcdConfigabcd
Method 3:
Another approach to replace all occurrences of a substring in a string is to use the re.sub() function/method from the re module in python.
import redef replace_substring(test_str, s1, s2): # Replacing all occurrences of substring s1 with s2 test_str = re.sub(s1, s2, test_str) return test_str# testtest_str = "CodeConfig"s1 = "Code"s2 = "abcd"print(replace_substring(test_str, s1, s2)) |
abcdConfig
Explanation: where n is the length of the input string. This is because the re.sub() function/method iterates through the entire input string and performs a regular expression match enabled each character to find all occurrences of the substring. The number of iterations is directly proportional to the length of the input string.
Method 4:
Using simple iteration
The idea behind this approach is to iterate through the input string character by character and check if each substring of length m matches the substring we may be interested to replace. If it does, we add the replacement substring to our result and move the pointer forward by m characters. If it doesn’t match, we add the current character to the result and move the pointer forward by 1 character.
def replace_substring(test_str, s1, s2): # Initialize an empty string to store the result result = "" # Initialize a variable to Keep the track of our position in the string i = 0 # Loop through the string one character at a time while i < len(test_str): # Check if the current substring matches the substring we may be interested to replace if test_str[i:i+len(s1)] == s1: # If it does, add the replacement substring to the result and move the pointer forward result += s2 i += len(s1) else: # If it doesn't, add the current character to the result and move the pointer forward result += test_str[i] i += 1 # Return the final result return result# testtest_str = "CodeConfig"s1 = "Code"s2 = "abcd"print(replace_substring(test_str, s1, s2)) |
abcdConfig
Explanation: where n is the length of the input string and m is the length of the substring to be replaced.
No comments:
Post a Comment