If you are flying into London, you will most likely be landing at London Heathrow (LHR). From there, you should take the Paddington Express train into central London and then a taxi to Kings Cross Station to catch a train towards Edinburgh.
If you are flying into Scotland, you will most likely be landing at Edinbught (EDI).
From Edinburgh, there are several options to get to St Andrews:
When taking the train to St Andrews, you will disembark in Leuchars, which is the nearest town with a train station. The 99 bus runs from Leuchars into St Andrews every 15 minutes, except for between midnight and 6:00 AM (Checkout the Lothian Buses Website). During most of the day there will also be taxis lined up outside of the Leuchars train station.
Visitors looking to travel to or from Edinburgh should look out for the X58, X59, and X60 route from Stagecoach Buses, which take around two hours.
You can reliably find taxis near Waverly Train Station in the city center of Edinburgh. Taxi fares to Edinburgh range from £50-£70. Ubers are also available but less reliable outside of the city center.
If you are arriving into Leuchars late at night, you should arrange to be picked up by a taxi.