{"id":4875,"date":"2021-09-20T08:00:37","date_gmt":"2021-09-20T08:00:37","guid":{"rendered":"https:\/\/tst-amo.net.ua\/blog\/?p=4875"},"modified":"2021-09-24T10:55:35","modified_gmt":"2021-09-24T10:55:35","slug":"4875","status":"publish","type":"post","link":"https:\/\/tst-amo.net.ua\/blog\/?p=4875","title":{"rendered":"Python3"},"content":{"rendered":"<h3>\u0412\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b<\/h3>\n<pre>Object type        Example literals\/creation\r\nNumbers            1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction()\r\nStrings            'spam', \"Bob's\", b'a\\x01c', u'sp\\xc4m'\r\nLists              [1, [2, 'three'], 4.5], list(range(10))\r\nDictionaries       {'food': 'spam', 'taste': 'yum'}, dict(hours=10)\r\nTuples             (1, 'spam', 4, 'U'), tuple('spam'), namedtuple\r\nFiles              open('eggs.txt'), open(r'C:\\ham.bin', 'wb')\r\nSets               set('abc'), {'a', 'b', 'c'}\r\nOther core types   Booleans, types, None<\/pre>\n<h4>Numbers<\/h4>\n<pre>&gt;&gt;&gt; 123 + 222 # Integer addition\r\n345\r\n&gt;&gt;&gt; 1.5 * 4 # Floating-point multiplication\r\n6.0\r\n&gt;&gt;&gt; 2 ** 100 # 2 to the power 100, again\r\n1267650600228229401496703205376<\/pre>\n<pre>&gt;&gt;&gt; len(str(2 ** 1000000)) # How many digits in a really BIG number?\r\n301030<\/pre>\n<pre>start experimenting with floating-point\r\nnumbers, you\u2019re likely to stumble across something that may look a bit odd at first\r\nglance:\r\n&gt;&gt;&gt; 3.1415 * 2 # repr: as code (Pythons &lt; 2.7 and 3.1)\r\n6.2830000000000004\r\n&gt;&gt;&gt; print(3.1415 * 2) # str: user-friendly\r\n6.283<\/pre>\n<pre>&gt;&gt;&gt; import math\r\n&gt;&gt;&gt; math.pi\r\n3.141592653589793\r\n&gt;&gt;&gt; math.sqrt(85)\r\n9.219544457292887<\/pre>\n<pre>&gt;&gt;&gt; import random\r\n&gt;&gt;&gt; random.random()\r\n0.7082048489415967\r\n&gt;&gt;&gt; random.choice([1, 2, 3, 4])\r\n1<\/pre>\n<h4>String<\/h4>\n<pre>&gt;&gt;&gt; S = 'Spam' # Make a 4-character string, and assign it to a name\r\n&gt;&gt;&gt; len(S) # Length\r\n4\r\n&gt;&gt;&gt; S[0] # The first item in S, indexing by zero-based position\r\n'S'\r\n&gt;&gt;&gt; S[1] # The second item from the left\r\n'p'<\/pre>\n<p>In Python, we can also index backward, from the end\u2014positive indexes count from<br \/>\nthe left, and negative indexes count back from the right:<\/p>\n<pre>&gt;&gt;&gt; S[-1] # The last item from the end in S\r\n'm'\r\n&gt;&gt;&gt; S[-2] # The second-to-last item from the end\r\n'a'<\/pre>\n<p>Formally, a negative index is simply added to the string\u2019s length, so the following two<br \/>\noperations are equivalent (though the first is easier to code and less easy to get wrong):<\/p>\n<pre>&gt;&gt;&gt; S[-1] # The last item in S\r\n'm'\r\n&gt;&gt;&gt; S[len(S)-1] # Negative indexing, the hard way\r\n'm'<\/pre>\n<p>In addition to simple positional indexing, sequences also support a more general form<br \/>\nof indexing known as slicing, which is a way to extract an entire section (slice) in a single<br \/>\nstep. For example:<\/p>\n<pre>&gt;&gt;&gt; S # A 4-character string\r\n'Spam'\r\n&gt;&gt;&gt; S[1:3] # Slice of S from offsets 1 through 2 (not 3)\r\n'pa'<\/pre>\n<pre>&gt;&gt;&gt; S[1:] # Everything past the first (1:len(S))\r\n'pam'\r\n&gt;&gt;&gt; S # S itself hasn't changed\r\n'Spam'\r\n&gt;&gt;&gt; S[0:3] # Everything but the last\r\n'Spa'\r\n&gt;&gt;&gt; S[:3] # Same as S[0:3]\r\n'Spa'\r\n&gt;&gt;&gt; S[:-1] # Everything but the last again, but simpler (0:-1)\r\n'Spa'\r\n&gt;&gt;&gt; S[:] # All of S as a top-level copy (0:len(S))\r\n'Spam'<\/pre>\n<pre>&gt;&gt;&gt; S + 'xyz' # Concatenation\r\n'Spamxyz'\r\n&gt;&gt;&gt; S # S is unchanged\r\n'Spam'\r\n&gt;&gt;&gt; S * 8 # Repetition\r\n'SpamSpamSpamSpamSpamSpamSpamSpam'<\/pre>\n<h4>Immutability<\/h4>\n<p>Also notice in the prior examples that we were not changing the original string with<br \/>\nany of the operations we ran on it. Every string operation is defined to produce a new<br \/>\nstring as its result, because strings are immutable in Python\u2014they cannot be changed<br \/>\nin place after they are created. In other words, you can never overwrite the values of<br \/>\nimmutable objects. For example, you can\u2019t change a string by assigning to one of its<br \/>\npositions, but you can always build a new one and assign it to the same name. Because<br \/>\nPython cleans up old objects as you go (as you\u2019ll see later), this isn\u2019t as inefficient as it<br \/>\nmay sound:<\/p>\n<pre>&gt;&gt;&gt; S\r\n'Spam'\r\n&gt;&gt;&gt; S[0] = 'z' # Immutable objects cannot be changed\r\n...error text omitted...\r\nTypeError: 'str' object does not support item assignment\r\n&gt;&gt;&gt; S = 'z' + S[1:] # But we can run expressions to make new objects\r\n&gt;&gt;&gt; S\r\n'zpam'<\/pre>\n<p>Every object in Python is classified as either <em>immutable (unchangeable)<\/em> or not. In terms<br \/>\nof the core types, <em>numbers<\/em>, <em>strings<\/em>, and <em>tuples<\/em> are immutable; <em>lists<\/em>, <em>dictionaries<\/em>, and<br \/>\n<em>sets<\/em> are not\u2014they can be changed in place freely, as can most new objects you\u2019ll code<br \/>\nwith classes.<\/p>\n<p>Strictly speaking, you can change text-based data in place if you either expand it into a<br \/>\nlist of individual characters and join it back together with nothing between, or use the<br \/>\nnewer bytearray type available in Pythons 2.6, 3.0, and later:<\/p>\n<pre>&gt;&gt;&gt; S = 'shrubbery'\r\n&gt;&gt;&gt; L = list(S) # Expand to a list: [...]\r\n&gt;&gt;&gt; L\r\n['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']\r\n&gt;&gt;&gt; L[1] = 'c' # Change it in place\r\n&gt;&gt;&gt; ''.join(L) # Join with empty delimiter\r\n'scrubbery'\r\n&gt;&gt;&gt; B = bytearray(b'spam') # A bytes\/list hybrid (ahead)\r\n&gt;&gt;&gt; B.extend(b'eggs') # 'b' needed in 3.X, not 2.X\r\n&gt;&gt;&gt; B # B[i] = ord(c) works here too\r\nbytearray(b'spameggs')\r\n&gt;&gt;&gt; B.decode() # Translate to normal string\r\n'spameggs'<\/pre>\n<h4>Type-Specific Methods<\/h4>\n<p>For example, the string find method is the basic substring search operation (it returns<br \/>\nthe offset of the passed-in substring, or \u22121 if it is not present), and the string replace<br \/>\nmethod performs global searches and replacements; both act on the subject that they<br \/>\nare attached to and called from:<\/p>\n<pre>&gt;&gt;&gt; S = 'Spam'\r\n&gt;&gt;&gt; S.find('pa') # Find the offset of a substring in S\r\n1\r\n&gt;&gt;&gt; S\r\n'Spam'\r\n&gt;&gt;&gt; S.replace('pa', 'XYZ') # Replace occurrences of a string in S with another\r\n'SXYZm'\r\n&gt;&gt;&gt; S\r\n'Spam'<\/pre>\n<pre>&gt;&gt; line = 'aaa,bbb,ccccc,dd'\r\n&gt;&gt;&gt; line.split(',') # Split on a delimiter into a list of substrings\r\n['aaa', 'bbb', 'ccccc', 'dd']\r\n&gt;&gt;&gt; S = 'spam'\r\n&gt;&gt;&gt; S.upper() # Upper- and lowercase conversions\r\n'SPAM'\r\n&gt;&gt;&gt; S.isalpha() # Content tests: isalpha, isdigit, etc.\r\nTrue\r\n&gt;&gt;&gt; line = 'aaa,bbb,ccccc,dd\\n'\r\n&gt;&gt;&gt; line.rstrip() # Remove whitespace characters on the right side\r\n'aaa,bbb,ccccc,dd'\r\n&gt;&gt;&gt; line.rstrip().split(',') # Combine two operations\r\n['aaa', 'bbb', 'ccccc', 'dd']<\/pre>\n<p>Notice the last command here\u2014it strips before it splits because Python runs from left<br \/>\nto right, making a temporary result along the way. Strings also support an advanced<br \/>\nsubstitution operation known as formatting, available as both an expression (the original)<br \/>\nand a string method call (new as of 2.6 and 3.0); the second of these allows you<br \/>\nto omit relative argument value numbers as of 2.7 and 3.1:<\/p>\n<pre>&gt;&gt; '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expression (all)\r\n'spam, eggs, and SPAM!'\r\n&gt;&gt;&gt; '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting method (2.6+, 3.0+)\r\n'spam, eggs, and SPAM!'\r\n&gt;&gt;&gt; '{}, eggs, and {}'.format('spam', 'SPAM!') # Numbers optional (2.7+, 3.1+)\r\n'spam, eggs, and SPAM!'<\/pre>\n<p>Formatting is rich with features, which we\u2019ll postpone discussing until later in this<br \/>\nbook, and which tend to matter most when you must generate numeric reports:<\/p>\n<pre>&gt;&gt;&gt; '{:,.2f}'.format(296999.2567) # Separators, decimal digits\r\n'296,999.26'\r\n&gt;&gt;&gt; '%.2f | %+05d' % (3.14159, \u221242) # Digits, padding, signs\r\n'3.14 | \u22120042'<\/pre>\n<div class=\"pdfprnt-buttons pdfprnt-buttons-post pdfprnt-bottom-right\"><a href=\"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=wpv2posts4875&print=pdf\" class=\"pdfprnt-button pdfprnt-button-pdf\" target=\"_blank\"><img decoding=\"async\" src=\"https:\/\/tst-amo.net.ua\/blog\/wp-content\/plugins\/pdf-print\/images\/pdf.png\" alt=\"image_pdf\" title=\"View PDF\" \/><\/a><a href=\"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=wpv2posts4875&print=print\" class=\"pdfprnt-button pdfprnt-button-print\" target=\"_blank\"><img decoding=\"async\" src=\"https:\/\/tst-amo.net.ua\/blog\/wp-content\/plugins\/pdf-print\/images\/print.png\" alt=\"image_print\" title=\"Print Content\" \/><\/a><\/div>","protected":false},"excerpt":{"rendered":"<p>\u0412\u0441\u0442\u0440\u043e\u0435\u043d\u043d\u044b\u0435 \u043e\u0431\u044a\u0435\u043a\u0442\u044b Object type Example literals\/creation Numbers 1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction() Strings &#8216;spam&#8217;, &#8220;Bob&#8217;s&#8221;, b&#8217;a\\x01c&#8217;, u&#8217;sp\\xc4m&#8217; Lists [1, [2, &#8216;three&#8217;], 4.5], list(range(10)) Dictionaries {&#8216;food&#8217;: &#8216;spam&#8217;, &#8216;taste&#8217;: &#8216;yum&#8217;}, dict(hours=10) Tuples (1, &#8216;spam&#8217;, 4, &#8216;U&#8217;), tuple(&#8216;spam&#8217;), namedtuple Files open(&#8216;eggs.txt&#8217;), open(r&#8217;C:\\ham.bin&#8217;, &#8216;wb&#8217;) Sets set(&#8216;abc&#8217;), {&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;} Other core types Booleans, types, None Numbers &gt;&gt;&gt; 123 &#8230;<\/p>\n<p><a href=\"https:\/\/tst-amo.net.ua\/blog\/?p=4875\" class=\"more-link\">Continue reading &lsquo;Python3&rsquo; &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4875","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4875"}],"collection":[{"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4875"}],"version-history":[{"count":16,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4875\/revisions"}],"predecessor-version":[{"id":4895,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=\/wp\/v2\/posts\/4875\/revisions\/4895"}],"wp:attachment":[{"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4875"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4875"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tst-amo.net.ua\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4875"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}