<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sun, 06 Feb 2022 16:52:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>What does the double star operator mean in Python?</title>
		<link>https://codepills.com/what-does-the-double-star-operator-mean-in-python/</link>
					<comments>https://codepills.com/what-does-the-double-star-operator-mean-in-python/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 01 Feb 2022 16:40:19 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[**kwargs]]></category>
		<category><![CDATA[double star]]></category>
		<category><![CDATA[double-asterisk]]></category>
		<category><![CDATA[method arguments]]></category>
		<category><![CDATA[power operator]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python functions]]></category>
		<category><![CDATA[two stars]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1283</guid>

					<description><![CDATA[In some Python code, you might spot double stars standing next to each other. What do those two stars mean, and what is their job? We will answer all the questions in this article. <a href="https://codepills.com/what-does-the-double-star-operator-mean-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In some Python code, you might spot double stars standing next to each other. What do those two stars mean, and what is their job? We will answer all the questions in this article.</p>
<p><span id="more-1283"></span></p>
<h2>Introduction</h2>
<p>Double star or double asterisk (**) in Python code can mean two different things based on the position in the code. First, if a double asterisk stands in the equation, it is part of it and is considered a <strong>Power operator</strong>. Otherwise, double-asterisk can occur in function and method argument input, and in such a case, it should be followed by <b>kwargs</b> shortcut (keyword arguments).</p>
<h2>Power Operator</h2>
<h3>What is double start operator in equation?</h3>
<p>Double star (or double-asterisk) in mathematical equation is one of the arithmetic operator (like +, -, *, **, /, //, %) in Python programming language. Double stars are also known as <strong>Power operator</strong>.</p>
<h3>What Power Operator does?</h3>
<p>For numerical data types Power operator works as an Exponential operator &#8211; anything on the right is the power of the left side.</p>
<p>Rather than talking about it, let&#8217;s demonstrate the Exponential operator on example:</p>
<pre><code class="language-python">two = 2
three = 3
# We can read the following notation as two to the power of the three
result = two ** three
# Result is according to the math laws, and it is equal to 2 * 2 * 2
print(result)

# Example of using double asterisk operator.
result_2 = 10 * (4 ** 2) - (2 ** 2) * 20
print(result_2)</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">8
80</code></pre>
<h2>What is the order of arithmetic operators?</h2>
<p>Arithmetic operators in Python follow the same precedence rule as in mathematics. The order is as follows: first performs exponential operator, then multiplication and division; as last executed are addition and subtraction, retrospectively.</p>
<p>Arithmetic operators ordered in decreasing order by priority:</p>
<pre><code class="language-bash">() -> ** -> * -> / -> // ->  % -> + -> -</code></pre>
<h2>** as variable argument length in functions and methods</h2>
<p>Interestingly, in Python, two starts fulfil also a different role. In Python&#8217;s function and method definition, the double-asterisk is also known for its role in defining variable argument length. Double asterisk concatenate with <i>kwargs</i> word and form <b><i>**kwargs</i></b>. So every time you see it, it means that the method or function it contains has a variable-length argument dictionary in the place of <b><i>**kwargs</i></b> occurrence. So when we use <i>**kwargs</i> as a parameter, we don&#8217;t need to know how many arguments we will need to pass to a function/method.</p>
<p>Btw. kwargs is not a Python reserved word and can be used in Python code independently.</p>
<h3>**kwargs examples</h3>
<p>Let&#8217;s write a simple function with <i>**kwargs</i>, taking various length arguments and passing them to a function.</p>
<pre><code class="language-java">def function(**kwargs):
    for key, value in kwargs.items():
        print("key: {} - value: {}".format(key, value))

function(pos1="John", pos2="Thomas", pos3="Paul")</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">key: pos1 - value: John
key: pos2 - value: Thomas
key: pos3 - value: Paul</code></pre>
<p>And now, let&#8217;s use the same function with additional arguments. Then, we will see how the function with <i>**kwargs</i> will accept a different number of arguments:</p>
<pre><code class="language-java">def function(**kwargs):
    for key, value in kwargs.items():
        print("key: {} - value: {}".format(key, value))

function(pos1="John", pos2="Thomas", pos3="Paul", pos4="Isabella", pos5="Carry", pos6="Angela")</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">key: pos1 - value: John
key: pos2 - value: Thomas
key: pos3 - value: Paul
key: pos4 - value: Isabella
key: pos5 - value: Carry
key: pos6 - value: Angela</code></pre>
<p><b>Note</b>: It is a good idea to create functions that accept <i>**kwargs</i> where you expect the number of inputs within the argument list to remain relatively small.</p>
<h2>Conclusion</h2>
<p>This article has shown two different ways how the double asterisk is used. First, we have seen the order of arithmetic operators in Python and how a double asterisk denotes a mathematical Power operator. The second usage is variable argument length in Python&#8217;s functions and class methods. Usage of <b><i>**kwargs</i></b> provides us flexibility to use keyword arguments in our program.</p>
<p>Did you find the usage of double stars in Python confusing? Do you have any tricks or know another way <u>how to use double stars in Python</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/what-does-the-double-star-operator-mean-in-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python String split() Method</title>
		<link>https://codepills.com/python-string-split-method/</link>
					<comments>https://codepills.com/python-string-split-method/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 07 May 2017 15:24:23 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=858</guid>

					<description><![CDATA[From time to time, you will find yourself trying to get a list of things from a string. For this purpose, you can use the split() function. How to use Python split function The first split function parameter is a &#8230; <a href="https://codepills.com/python-string-split-method/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>From time to time, you will find yourself trying to get a list of things from a string. For this purpose, you can use the split() function.</p>
<p><span id="more-858"></span></p>
<h2>How to use Python split function</h2>
<p>The first split function parameter is a separator, character on which the division of string will be happening. If the split function has an empty separator character, whitespace will be used as default splitting character. Let&#8217;s look at the example:</p>
<pre class="">s = 'And now something completely different...'
print(s.split())
# ['And', 'now', 'something', 'completely', 'different...']</pre>
<p>We can use also custom string as splitting string:</p>
<pre class="">s = 'spam, ham, sausages, spam, sausage - spam, spam with eggs'
print(s.split(", "))
# ['spam', 'ham', 'sausages', 'spam', 'sausage - spam', 'spam with eggs']</pre>
<p>What I personally consider the greatest plus of Python split method is actually a possibility to directly assign split string parts into the variable. Here is a nice example:</p>
<pre class="">s = 'spam, ham, eggs'
x, y, z = s.split(", ")
print(x)
# spam
print(y)
# ham
print(z)
# eggs</pre>
<p>Splitting the string is opposite of concatenation. If you want to concatenate the strings, check the guide <a href="http://codekopf.com/python/concatenate-append-strings-python/">how to concatenate the strings</a> in the best way.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/python-string-split-method/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to concatenate or append strings in Python</title>
		<link>https://codepills.com/concatenate-append-strings-python/</link>
					<comments>https://codepills.com/concatenate-append-strings-python/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 07 May 2017 05:59:36 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=850</guid>

					<description><![CDATA[If you are looking for answer how to append strings in Python, you are on the right page. There are several different ways how to concatenate strings in Python. Pick up the right one which will most suit to your code &#8230; <a href="https://codepills.com/concatenate-append-strings-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>If you are looking for answer how to append strings in Python, you are on the right page.<br />
<span id="more-850"></span><br />
There are several different ways how to concatenate strings in Python. Pick up the right one which will most suit to your code purpose.</p>
<h2>Concatenation with + operator</h2>
<p>First way is to use + operator for concatenation:</p>
<pre class="">s  = 'And '
s += 'now '
s += 'something '
s += 'completely '
s += 'different.'
print(s)
</pre>
<p>Since everything in Python is an object and Strings in Python in immutable, this solution is unoptimized. Every time the + operator is called reference on new object is assigned to variable. It is sufficient to use it for simple programs. For more complex programs requiring building lots of text I would recommend to use less resource requiring approach.</p>
<h2>Building strings with .append()</h2>
<p>Second option is to use approach for building up string from a list. If you are familiar with Java&#8217;s OOP approach, StringBuilder is similar way to build strings in Java.</p>
<p>Idea is simple. First create list of all append-able strings and then use str.join() method to concatenate them all at the end:</p>
<pre class="">l = []
l.append('And')
l.append('now')
l.append('something')
l.append('completely')
l.append('different.')
s = ''.join(l)
print(s)
# And now something completely different.</pre>
<p>Difference between string concatenation with + operator and building string over append is in performance. Despite in short text the performance difference is none, in longer text building strings over append will create new string in one go while + operator build string over and over, repetitively.</p>
<h2>.append vs. + operator</h2>
<p>Here I made a small code to test which operation for concatenating strings is faster:</p>
<pre class="">import time

# append in loop
app_start = int(round(time.time() * 1000))
l = []
for _ in range(0,10000000,1):
    l.append('a')
string = ''.join(l)
app_end = int(round(time.time() * 1000))
print('With append: %s' % (app_end - app_start))

# conc with +
plus_start = int(round(time.time() * 1000))
s = ''
for _ in range(0,10000000,1):
    s += 'a'
plus_end = int(round(time.time() * 1000))
print('With +: %s' % (plus_end - plus_start))</pre>
<p>I run the code on my Mac Pro which is mid 2015 configuration. The results are in microseconds:</p>
<table>
<tbody>
<tr>
<td>Rounds</td>
<td>.append</td>
<td>+ operator</td>
</tr>
<tr>
<td>1 000</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1 000 000</td>
<td>150</td>
<td>185</td>
</tr>
<tr>
<td>10 000 000</td>
<td>1460</td>
<td>1980</td>
</tr>
</tbody>
</table>
<p>It is obvious that for small number of rounds there is no difference between .append or + operator. But with increasing complexity (increasing number of rounds) appending strings to list will be slightly faster by nearly quarter.</p>
<h2>Using .join()</h2>
<p>You can also use strings in join function directly:</p>
<pre class="">s1 = "And now something "
s2 = "completely different."
s = " ".join((s1, s2))
print(s)
# And now something completely different.</pre>
<h2>Padding</h2>
<p>One of the most simplest way is just pad strings into the new string. We can use either the % operator for padding in exact order or use .format() method to define unique keywords and place them in arbitrary order:</p>
<pre class="">s1 = 'And now something'
s2 = 'completely different'

new_s1 = "Sentence: %s %s" % (s1, s2)
print(new_s1)
# Sentence: And now something completely different.

new_s2 = "Sentence: {string2} {string1}".format(string1=s1, string2=s2)
print(new_s2)
# Sentence: completely different And now something.</pre>
<p>&nbsp;</p>
<h2>Using __add__ method</h2>
<p>Marvel of Python is its neat variability. Since everything in Python is the object we can use object&#8217;s __add__ method for concatenation. Using s1.__add__(s2) is identical with using a+b.</p>
<pre class="">s1='And now something '
s2='completely different.'
s = s1.__add__(s2)
print(s)
# Sentence: And now something completely different.</pre>
<p>When you concatenate strings using the + operator, Python will call the __add__ method while on the string on the left side passing the right side string as a parameter. So using this method on simple strings is code overkill.</p>
<p>It make much more sense to use it for concatenation object properties.</p>
<pre class="">class Sentence(object):
  def __init__(self, part):
     self.part = part
  def __add__(self, other):
     total = self.part + ' ' + other.part
     return Sentence(total)

  def __radd__(self, other):
     if other == 0:
       return self
     else:
       return self.__add__(other)

  def __str__(self):
     return "Sentence: %s" % (self.part)

s1 = Sentence('And now')
s2 = Sentence('something completely different.')
print(s1)
# Sentence: And now
print(s2)
# Sentence: something completely different.

s = s1 + s2
print(s)
# Sentence: And now something completely different.

super_s = sum([s, s1, s2])
print(super_s)
# Sentence: And now something completely different. And now something completely different.</pre>
<p>As we saw in the previous section there are several ways how to append strings or concatenate them together. You can use literally any provided solution here, it only depends on a purpose and necessary complexity you want to implement in your program.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/concatenate-append-strings-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
