0

Hey guys im trying to create a api request from a script like this:

 ticket = [] 
 for x in result:
     ticket.append(x) 
 for t in ticket:
     sport = int(t['Sport'])
     location = int(t['Location'])
     league = str(t['League'])[1:].strip()
     print(league)
     x = requests.post('http://server1:5099/Leagues?alias={league}&sportId={sport}'.format(league=league.strip(),sport=sport))
     print(x.status_code)

im getting 404 error an when im debugging the code i see that the league is printed like this: "'Spain Cup. Women'" i need to remove the white spaces and the quotes from the league string so that the api request will look like this:

http://server1:5099/Leagues?alias=SpainCup.Women&sportId=48242

Thanks!

Eternal
  • 928
  • 9
  • 22
Jacob
  • 3
  • 5
  • Any reason you're not using `data={'alias': league, 'sportId': sport}` instead of building your query string manually? – Jon Clements Feb 12 '20 at 09:01
  • Does this answer your question? [Remove all whitespace in a string in Python](https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python) – Capie Feb 12 '20 at 09:04

3 Answers3

0

You can use String replace method for that purpose. If you'd like to remove space from the string, you do it like this way:

serverUrlRequest="your server request url"
correctSrvUrl=serverUrlRequest.replace(" ", "")

This will replace all the white spaces in the url. You can do the same for quotes.

Dinesh Neupane
  • 382
  • 10
  • 19
0

You can do something like this:

s = "'Spain Cup. Women'"
s = s.replace(' ', '').replace('\'', '')

The code above will transform your "'Spain Cup. Women'" string into 'SpainCup.Women'

Yegor
  • 13
  • 4
  • Hey , i did tried to change the request to this: x = requests.post(url='http://icdataproducts1:5099/Leagues?alias={league}&sportId={sport}',data={'alias':league.replace(' ', '').replace('\'', ''),'sportId': sport}) still getting this value : "'Spain Cup. Women'" – Jacob Feb 12 '20 at 09:13
  • Hm.. According to this `x = requests.post(url='icdataproducts1:5099/Leagues?alias={league}&sportId={sport}',data={'alias':league.replace(' ', '').replace('\'', ''),'sportId': sport})`, you're removing quotes and whitespace only in data dictionary, not in url string. Try to strip league string like this `league = league.replace(' ', '').replace('\'', '')` and then use this string in your request url and body `x = requests.post(url='icdataproducts1:5099/Leagues?alias={league}&sportId={sport}'.format(league=league, sport=sport), data={'alias':league, 'sportId': sport})` – Yegor Feb 12 '20 at 09:22
0

If you wind up removing many characters, it can be easier to use regular expressions than a series of replaces. This will remove quotes, apostrophes, spaces:

import re
correctSrvUrl = re.sub('[\s\'"]', '', serverUrlRequest)
Tim Nyborg
  • 1,599
  • 1
  • 9
  • 16