How To Pass A String To A Function In Python

In this tutorial, we will learn how to pass a string to a function in Python. Python is a versatile and powerful programming language, allowing us to work effectively with various types of data structures, including strings.

Since strings are commonly used to store and manipulate textual data, it’s essential to understand how to pass them as function arguments.

1. Define the function with the parameter

First, you’ll need to define a function with a parameter. This parameter will accept the input string when calling the function. In Python, you can define a function using the def keyword, followed by the function name, parentheses containing the parameter name, and a colon.

Let’s define a simple function named display_string which has one parameter called input_string.

2. Write the function body

Next, you can write the function body to perform the required operation using the input string passed as an argument. In our case, the function will simply print the input string.

3. Call the function with a string argument

Now that your function is defined, it’s time to call it using a string argument. You can do this by writing the name of the function followed by parentheses, containing the string you want to pass to the function. You can pass the string either by directly specifying it within the parentheses, or by assigning it to a variable and passing the variable as an argument.

In this example, we pass the string “Hello, World!” as a direct argument to the display_string function:

Alternatively, you can pass a string variable to the function:

In both cases, the display_string function will receive the input string and print the output.

4. Test the function

Let’s combine the function definition and function call into a single script, and test the output:

When executed, the script will output:

Hello, World!


In this tutorial, we learned how to pass a string to a function in Python. By defining a function with a string parameter and calling it with a string argument, you can efficiently manipulate and process textual data within your Python application.