Python Return String From Function

5/5 - (2 votes)

Do you need to create a function that returns a string but you don’t know how? No worries, in sixty seconds, you’ll know! Go! πŸš€

A Python function can return any object such as a string. To return a string, create the string object within the function body, assign it to a variable my_string, and return it to the caller of the function using the keyword operation return my_string. Or simply create the string within the return expression like so: return "hello world"

def f():
    return 'hello world'

# hello world

Create String in Function Body

Let’s have a look at another example:

The following code creates a function create_string() that iterates over all numbers 0, 1, 2, …, 9, appends them to the string my_string, and returns the string to the caller of the function:

def create_string():
    ''' Function to return string '''
    my_string = ''
    for i in range(10):
        my_string += str(i)
    return my_string

s = create_string()
# 0123456789

Note that you store the resulting string in the variable s. The local variable my_string that you created within the function body is only visible within the function but not outside of it.

So, if you try to access the name my_string, Python will raise a NameError:

>>> print(my_string)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
NameError: name 'my_string' is not defined

To fix this, simply assign the return value of the function — a string — to a new variable and access the content of this new variable:

>>> s = create_string()
>>> print(s)

There are many other ways to return a string in Python.

Return String With List Comprehension

For example, you can use a list comprehension in combination with the string.join() method instead that is much more concise than the previous code—but creates the same string of digits:

def create_string():
    ''' Function to return string '''
    return ''.join([str(i) for i in range(10)])

s = create_string()
# 0123456789

For a quick recap on list comprehension, feel free to scroll down to the end of this article.

You can also add some separator strings like so:

def create_string():
    ''' Function to return string '''
    return ' xxx '.join([str(i) for i in range(10)])

s = create_string()
# 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9

Return String with String Concatenation

You can also use a string concatenation and string multiplication statement to create a string dynamically and return it from a function.

Here’s an example of string multiplication:

def create_string():
    ''' Function to return string '''
    return 'ho' * 10

s = create_string()
# hohohohohohohohohoho

String Concatenation of Function Arguments

Here’s an example of string concatenation that appends all arguments to a given string and returns the result from the function:

def create_string(a, b, c):
    ''' Function to return string '''
    return 'My String: ' + a + b + c

s = create_string('python ', 'is ', 'great')
# My String: python is great

Concatenate Arbitrary String Arguments and Return String Result

You can also use dynamic argument lists to be able to add an arbitrary number of string arguments and concatenate all of them:

def create_string(*args):
    ''' Function to return string '''
    return ' '.join(str(x) for x in args)

print(create_string('python', 'is', 'great'))
# python is great

print(create_string(42, 41, 40, 41, 42, 9999, 'hi'))
# 42 41 40 41 42 9999 hi

Background List Comprehension

πŸ’‘ Knowledge: List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax [expression context]. You iterate over all elements in a given context “for i in range(10)“, and apply a certain expression, e.g., the identity expression i, before adding the resulting values to the newly-created list.

In case you need to learn more about list comprehension, feel free to check out my explainer video:

A Simple Introduction to List Comprehension in Python

Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist?

A: An extroverted computer scientist looks at your shoes when he talks to you.