It is well known that a jostled string tends to become knotted; yet the factors governing the "spontaneous" formation of various knots are unclear. We performed experiments in which a string was tumbled inside a box and found that complex knots often form within seconds. We used mathematical knot theory to analyze the knots. Above a critical string length, the probability P of knotting at first increased sharply with length but then saturated below 100%. This behavior differs from that of mathematical self-avoiding random walks, where P has been proven to approach 100%. Finite agitation time and jamming of the string due to its stiffness result in lower probability, but P approaches 100% with long, flexible strings. We analyzed the knots by calculating their Jones polynomials via computer analysis of digital photos of the string. Remarkably, almost all were identified as prime knots: 120 different types, having minimum crossing numbers up to 11, were observed in 3,415 trials. All prime knots with up to seven crossings were observed. The relative probability of forming a knot decreased exponentially with minimum crossing number and Möbius energy, mathematical measures of knot complexity. Based on the observation that long, stiff strings tend to form a coiled structure when confined, we propose a simple model to describe the knot formation based on random "braid moves" of the string end. Our model can qualitatively account for the observed distribution of knots and dependence on agitation time and string length.