Home > OS >  How do you cut the unwanted parts of a string
How do you cut the unwanted parts of a string

Time:07-08

When I run the code. The output is like "{'fact': "Cats are the world's most popular pets, outnumbering dogs by as many as three to one", 'length': 84}". How do I get rid of the 'fact:' at the front and 'length:' at the back. I just want the facts

import requests
import json
def get_fact():
  catFact = requests.get("https://catfact.ninja/fact?max_length=140")
  json_data = json.loads(catFact.text)
  return json_data
print(get_fact()) 

CodePudding user response:

Are you looking for:

import requests
import json
def get_fact():
  catFact = requests.get("https://catfact.ninja/fact?max_length=140")
  json_data = json.loads(catFact.text)
  return json_data['fact']  # <- HERE
print(get_fact()) 

Output:

Cats have "nine lives" thanks to a flexible spine and powerful leg and back muscles

Note: you don't need json module here, use json() method of Response instance returned by requests:

import requests
def get_fact():
  catFact = requests.get("https://catfact.ninja/fact?max_length=140").json()
  return catFact['fact']
print(get_fact())

CodePudding user response:

Short answer: you need to use either get_fact()['fact'] or get_fact().get('fact'). The former will throw an exception if fact doesn't exist whereas the latter will return None.

Why: In your code sample you fetch some json data, and then print out the entire bit of json. When you parse json, the output is a key/value map called a dictionary (or map or object in other languages). The dictionary in this case contains two keys: fact and length. If you only one want of the values, then you need to tell python that you want only a single value -- fact in this case.

Remember though: this wouldn't apply to every json object you read. Not every one is going to have a fact key.

CodePudding user response:

What you want is to access the key in the python dict you made with the json.loads call. We actually don't need the json library as requests can do json itself.

This code also does check the response was OK and fails with informative error message (following the https://peps.python.org/pep-0020/).

import requests
def get_fact():
  # Get the facts dictionary in a JSON serialized form.
  cat_fact_response = requests.get("https://catfact.ninja/fact?max_length=140")

  # Let the response raise the exception if something bad happened to the cat facts server connection.
  cat_fact_response.raise_for_status()

  # Deserialize the json (make a Python dict from the text we got). requests can do that on it's own:
  cat_fact_dict = cat_fact_response.json()

  # Access the fact from the json from the dictionary
  return cat_fact_dict['fact']

print(get_fact())
# python3 script.py 
The cat's tail is used to maintain balance.

CodePudding user response:

What you are returning(in get_fact) is a json object which you are then printing. You could just get the fact you want to print using

return json_data["fact"]

Below is a link to a w3 school resource on using json with python

link

  • Related