Sick Gaming
[Tut] Python Return String From Function - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python Return String From Function (/thread-100082.html)



[Tut] Python Return String From Function - xSicKxBot - 10-14-2022

Python Return String From Function

<div>
<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;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<p>Do you need to <strong>create a function that returns a string</strong> but you don’t know how? No worries, in sixty seconds, you’ll know! Go! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<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 – 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>
<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()
# hello world</pre>
<h2>Create String in Function Body</h2>
<p>Let’s have a look at another example:</p>
<p>The following code creates a function <code>create_string()</code> that iterates over all numbers 0, 1, 2, …, 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>
<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()
print(s)
# 0123456789
</pre>
<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>
<p>So, if you try to access the name <code>my_string</code>, Python will raise a <code>NameError</code>:</p>
<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)
Traceback (most recent call last): File "&lt;pyshell#1>", line 1, in &lt;module> print(my_string)
NameError: name 'my_string' is not defined</pre>
<p>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:</p>
<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()
>>> print(s)
0123456789</pre>
<p>There are many other ways to return a string in Python. </p>
<h2>Return String With List Comprehension</h2>
<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—but creates the same string of digits:</p>
<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()
print(s)
# 0123456789
</pre>
<p>For a quick recap on list comprehension, feel free to scroll down to the end of this article.</p>
<p>You can also add some separator strings like so:</p>
<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()
print(s)
# 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9
</pre>
<h2>Return String with String Concatenation</h2>
<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>
<p>Here’s an example of string multiplication:</p>
<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()
print(s)
# hohohohohohohohohoho
</pre>
<h2>String Concatenation of Function Arguments</h2>
<p>Here’s an example of string concatenation that appends all arguments to a given string and returns the result from the function:</p>
<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')
print(s)
# My String: python is great
</pre>
<h2>Concatenate Arbitrary String Arguments and Return String Result</h2>
<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>
<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'))
# python is great print(create_string(42, 41, 40, 41, 42, 9999, 'hi'))
# 42 41 40 41 42 9999 hi</pre>
<h2>Background List Comprehension</h2>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" 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 “<code>for i in range(10)</code>“, and apply a certain expression, e.g., the identity expression <code>i</code>, before adding the resulting values to the newly-created list.</p>
<p>In case you need to learn more about list comprehension, feel free to check out my explainer video:</p>
<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 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>
<h2>Programmer Humor</h2>
<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>
</div>


https://www.sickgaming.net/blog/2022/10/13/python-return-string-from-function/