Skip to Main Content
Blog

Reverse Words in Python

Reverse Words in Python

def main():
	"""
	Reverses each word in a string.
	"""

	# Prompt the user to enter a string and remove the trailing period if present
	txt = input("Enter string: ").rstrip(".")

	# Split the string into words
	units = txt.split()

	# Reverse each word in the list
	reversed_units = [unit[::-1] for unit in units]

	# Join the reversed words back into a single string
	reversed_txt = " ".join(reversed_units)

	# Print the result
	print(reversed_txt)


if __name__ == "__main__":
	main()