Python String - removeprefix() function
Last Updated :
05 Dec, 2024
Improve
Python String removeprefix() function removes the prefix and returns the rest of the string. If the prefix string is not found, then it returns the original string.
Example:
s1 = 'Geeks'.removeprefix("Gee")
print(s1)
Output:
ks
Let's take a deeper look at removeprefix():
Syntax:
string.removeprefix(prefix)
Parameters:
- string: The original string from which the prefix will be removed.
- prefix: The substring you want to remove from the start of the string.
- Return Type: The method returns a new string with the specified prefix removed, if it exists. If the string does not start with the given prefix, it simply returns the original string.
Example of removeprefix() method
We can remove a prefix string from a string using Python String removeprefix() Method. If the prefix is not the prefix in the string, the original string is returned.
# Basic Usage
s = "HelloWorld"
res = s.removeprefix("Hello")
print(res) # Output: World
# No Prefix Match
s = "PythonProgramming"
res = s.removeprefix("Java")
print(res) # Output: PythonProgramming
# Case Sensitivity
s = "PythonProgramming"
res = s.removeprefix("python")
print(res) # Output: PythonProgramming
Output:
World
PythonProgramming
PythonProgramming
Explanation:
- string "HelloWorld" has the prefix "Hello", so it removes it and returns "World".
- Since the string doesn't start with "Java", the original string is returned unchanged.
- The method is case-sensitive, so it does not remove "python" (lowercase) from "PythonProgramming" because the prefix "python" does not match the case of the actual string's prefix "Python".
Practical Applications of removeprefix()
- Cleaning Data: When processing files or strings with standard prefixes (like file paths, URLs, or formatted strings), removeprefix() can be used to cleanly remove unwanted prefixes.
- Processing URLs: In web scraping or web applications, you may need to strip a common domain prefix or protocol (http://, https://) from URLs.
- Automating String Parsing: In scenarios where strings are prefixed with specific identifiers, such as command-line arguments or data fields, removeprefix() can be helpful to automate the parsing.
- Processing Version Numbers: If version numbers are prefixed with a specific string (e.g., "v" for versions), removeprefix() can be used to extract just the version number.
- Code Example:
# Cleaning Data
p1 = "/home/user/documents/file.txt"
p2 = p1.removeprefix("/home/user/")
print(p2) # Output: documents/file.txt
# Removing URL Prefix
url1 = "https://example.com"
url2 = url.removeprefix("https://")
print(url2) # Output: example.com
# Parsing Command-Line Arguments
c = "cmd-12345"
id1 = "cmd-"
id2 = c.removeprefix(id1)
print(id2) # Output: 12345
# Removing Version Prefix
v1 = "v1.2.3"
v2 = v1.removeprefix("v")
print(v2) # Output: 1.2.3
Output:
documents/file.txt
example.com
12345
1.2.3