Python | Split URL from Query Parameters

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 develment 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


Output :

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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


Output :

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.