Skip to content
Related Articles

Related Articles

Python | Split URL from Query Parameters

Improve Article
Save Article
  • Last Updated : 07 Sep, 2022
Improve Article
Save Article

Sometimes, while web development, we can come across a task in which we may require to perform a split of query parameters from URLs which is done by ‘?’ character. This has application over web development as well as other domains which involve URLs. Lets discuss certain ways in which this task can be performed.
Method #1 : Using split() 
This is one of the way in which we can solve this problem. We split by ‘?’ and return the first part of split for result.
 

Python3




# Python3 code to demonstrate working of
# Split URL from Query Parameters
# Using split()
 
# initializing string
test_str = 'www.geeksforgeeks.org?is = best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Split URL from Query Parameters
# Using split()
res = test_str.split('?')[0]
 
# printing result
print("The base URL is : " + res)

Output : 

The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org

 

Time Complexity: O(n) -> (split function)

Auxiliary Space: O(n)

 
Method #2 : Using rfind() 
This is another way in which we need to perform this task. In this, we find the first occurrence of ‘?’ from right and slice the string.
 

Python3




# Python3 code to demonstrate working of
# Split URL from Query Parameters
# Using rfind()
 
# initializing string
test_str = 'www.geeksforgeeks.org?is = best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Split URL from Query Parameters
# Using rfind()
res = test_str[:test_str.rfind('?')]
 
# printing result
print("The base URL is : " + res)

Output : 

The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org

 

Time Complexity: O(n)

Auxiliary Space : O(n)

Method #3 : Using index().Finding index of ‘?’ and then used string slicing

Python3




# Python3 code to demonstrate working of
# Split URL from Query Parameters
# Using index()
 
# initializing string
test_str = 'www.geeksforgeeks.org?is = best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Split URL from Query Parameters
# Using index()
res = test_str[0:test_str.index('?')]
 
# printing result
print("The base URL is : " + res)

Output

The original string is : www.geeksforgeeks.org?is = best
The base URL is : www.geeksforgeeks.org

Time Complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!