10-14-2022, 01:13 PM
Python Return String From Function
5/5 – (1 vote)
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!![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
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, and return it to the caller of the function using the keywordoperation . Or simply create the string within the return expression like so:
Create String in Function Body
Let’s have a look at another example:
The following code creates a function that iterates over all numbers 0, 1, 2, …, 9, appendsthem to the string , and returns the string to the caller of the function:
Note that you store the resulting string in the variable. The localvariable 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, Python will raise a :
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:
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 method instead that is much more concise than the previous code—but creates the same string of digits:
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:
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:
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:
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:
Background List Comprehension
Knowledge: List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax . You iterate over all elements in a given context ““, and apply a certain expression, e.g., the identity expression , 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:
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg)
Programmer Humor
5/5 – (1 vote)
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!
![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
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
Code:
my_stringCode:
return my_stringCode:
return "hello world"Code:
def f(): return 'hello world' f()
# hello worldLet’s have a look at another example:
The following code creates a function
Code:
create_string()Code:
my_stringCode:
def create_string(): ''' Function to return string ''' my_string = '' for i in range(10): my_string += str(i) return my_string s = create_string()
print(s)
# 0123456789Note that you store the resulting string in the variable
Code:
sCode:
my_stringSo, if you try to access the name
Code:
my_stringCode:
NameErrorCode:
>>> print(my_string)
Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print(my_string)
NameError: name 'my_string' is not definedTo fix this, simply assign the return value of the function — a string — to a new variable and access the content of this new variable:
Code:
>>> s = create_string()
>>> print(s)
0123456789There 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
Code:
string.join()Code:
def create_string(): ''' Function to return string ''' return ''.join([str(i) for i in range(10)]) s = create_string()
print(s)
# 0123456789For 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:
Code:
def create_string(): ''' Function to return string ''' return ' xxx '.join([str(i) for i in range(10)]) s = create_string()
print(s)
# 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9You 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:
Code:
def create_string(): ''' Function to return string ''' return 'ho' * 10 s = create_string()
print(s)
# hohohohohohohohohohoHere’s an example of string concatenation that appends all arguments to a given string and returns the result from the function:
Code:
def create_string(a, b, c): ''' Function to return string ''' return 'My String: ' + a + b + c s = create_string('python ', 'is ', 'great')
print(s)
# My String: python is greatYou can also use dynamic argument lists to be able to add an arbitrary number of string arguments and concatenate all of them:
Code:
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
Knowledge: List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax Code:
[expression context]Code:
for i in range(10)Code:
iIn case you need to learn more about list comprehension, feel free to check out my explainer video:
Programmer Humor
Code:
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.
