{"id":128859,"date":"2022-10-13T13:35:50","date_gmt":"2022-10-13T13:35:50","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=784920"},"modified":"2022-10-13T13:35:50","modified_gmt":"2022-10-13T13:35:50","slug":"python-return-string-from-function","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/10\/13\/python-return-string-from-function\/","title":{"rendered":"Python Return String From Function"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;784920&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<p>Do you need to <strong>create a function that returns a string<\/strong> but you don&#8217;t know how? No worries, in sixty seconds, you&#8217;ll know! Go! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f680.png\" alt=\"\ud83d\ude80\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<p class=\"has-pale-cyan-blue-background-color has-background\">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_string<\/code>, and return it to the caller of the function using the <a title=\"Return Keyword in Python \u2013 A Simple Illustrated Guide\" rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-return\/\" target=\"_blank\">keyword <\/a>operation <code>return my_string<\/code>. Or simply create the string within the return expression like so: <code>return \"hello world\"<\/code> <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def f(): return 'hello world' f()\n# hello world<\/pre>\n<h2>Create String in Function Body<\/h2>\n<p>Let&#8217;s have a look at another example:<\/p>\n<p>The following code creates a function <code>create_string()<\/code> that iterates over all numbers 0, 1, 2, &#8230;, 9, <a title=\"Python List append() Method\" rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-append\/\" target=\"_blank\">appends <\/a>them to the string <code>my_string<\/code>, and returns the string to the caller of the function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(): ''' Function to return string ''' my_string = '' for i in range(10): my_string += str(i) return my_string s = create_string()\nprint(s)\n# 0123456789\n<\/pre>\n<p>Note that you store the resulting string in the variable <code>s<\/code>. The <a rel=\"noreferrer noopener\" title=\"Understanding Namespaces in Python\" href=\"https:\/\/blog.finxter.com\/understanding-namespaces-in-python\/\" target=\"_blank\">local <\/a>variable <code>my_string<\/code> that you created within the function body is only visible within the function but not outside of it. <\/p>\n<p>So, if you try to access the name <code>my_string<\/code>, Python will raise a <code>NameError<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> print(my_string)\nTraceback (most recent call last): File \"&lt;pyshell#1>\", line 1, in &lt;module> print(my_string)\nNameError: name 'my_string' is not defined<\/pre>\n<p>To fix this, simply assign the return value of the function &#8212; a string &#8212; to a new variable and access the content of this new variable:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> s = create_string()\n>>> print(s)\n0123456789<\/pre>\n<p>There are many other ways to return a string in Python. <\/p>\n<h2>Return String With List Comprehension<\/h2>\n<p>For example, you can use a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\">list comprehension<\/a> in combination with the <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-string-join\/\" data-type=\"post\" data-id=\"26062\" target=\"_blank\">string.join()<\/a><\/code> method instead that is much more concise than the previous code&#8212;but creates the same string of digits:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(): ''' Function to return string ''' return ''.join([str(i) for i in range(10)]) s = create_string()\nprint(s)\n# 0123456789\n<\/pre>\n<p>For a quick recap on list comprehension, feel free to scroll down to the end of this article.<\/p>\n<p>You can also add some separator strings like so:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(): ''' Function to return string ''' return ' xxx '.join([str(i) for i in range(10)]) s = create_string()\nprint(s)\n# 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9\n<\/pre>\n<h2>Return String with String Concatenation<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">You can also use a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-concatenation\/\" target=\"_blank\">string concatenation<\/a> and <a href=\"https:\/\/blog.finxter.com\/how-to-repeat-a-string-multiple-times-in-python\/\" data-type=\"post\" data-id=\"519561\" target=\"_blank\" rel=\"noreferrer noopener\">string multiplication<\/a> statement to create a string dynamically and return it from a function.<\/p>\n<p>Here&#8217;s an example of string multiplication:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(): ''' Function to return string ''' return 'ho' * 10 s = create_string()\nprint(s)\n# hohohohohohohohohoho\n<\/pre>\n<h2>String Concatenation of Function Arguments<\/h2>\n<p>Here&#8217;s an example of string concatenation that appends all arguments to a given string and returns the result from the function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(a, b, c): ''' Function to return string ''' return 'My String: ' + a + b + c s = create_string('python ', 'is ', 'great')\nprint(s)\n# My String: python is great\n<\/pre>\n<h2>Concatenate Arbitrary String Arguments and Return String Result<\/h2>\n<p>You can also use dynamic argument lists to be able to add an arbitrary number of string arguments and concatenate all of them:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def create_string(*args): ''' Function to return string ''' return ' '.join(str(x) for x in args) print(create_string('python', 'is', 'great'))\n# python is great print(create_string(42, 41, 40, 41, 42, 9999, 'hi'))\n# 42 41 40 41 42 9999 hi<\/pre>\n<h2>Background List Comprehension<\/h2>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Knowledge<\/strong>: List comprehension is a very useful Python feature that allows you to dynamically <a rel=\"noreferrer noopener\" title=\"How to Create a Python List?\" href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list\/\" target=\"_blank\">create a list<\/a> by using the syntax <code>[expression context]<\/code>. You <a href=\"https:\/\/blog.finxter.com\/iterators-iterables-and-itertools\/\" data-type=\"post\" data-id=\"29507\" target=\"_blank\" rel=\"noreferrer noopener\">iterate<\/a> over all elements in a given context &#8220;<code>for i in range(10)<\/code>&#8220;, and apply a certain expression, e.g., the identity expression <code>i<\/code>, before adding the resulting values to the newly-created list.<\/p>\n<p>In case you need to learn more about list comprehension, feel free to check out my explainer video:<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-return-string-from-function\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<h2>Programmer Humor<\/h2>\n<pre class=\"wp-block-preformatted has-global-color-8-background-color has-background\"><code><strong>Q<\/strong>: How do you tell an introverted computer scientist from an extroverted computer scientist? <strong>A<\/strong>: An extroverted computer scientist looks at <strong><em>your<\/em><\/strong> shoes when he talks to you.<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Do you need to create a function that returns a string but you don&#8217;t know how? No worries, in sixty seconds, you&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-128859","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128859","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128859"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128859\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128859"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128859"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128859"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}