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
.
1 |
def display_string(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.
1 2 |
def display_string(input_string): print(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:
1 |
display_string("Hello, World!") |
Alternatively, you can pass a string variable to the function:
1 2 |
my_string = "Hello, World!" display_string(my_string) |
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:
1 2 3 4 5 |
def display_string(input_string): print(input_string) my_string = "Hello, World!" display_string(my_string) |
When executed, the script will output:
Hello, World!
Conclusion
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.