Python basic grammar (miscellaneous)

2.7 base.

Built-in type

#integer
a = 10
i = -10
x = 0x55
b = 0x100110

#Floating point
f = 2.73

#Boolean
a = True
b = False

#Character string (immutable)
s = 'python'

#List (variable)
a = ['p','y','t','h','o','n']

#Tuple (immutable)
a = ('p','y','t','h','o','n')

#Dictionary (variable)
a = {'happy' : '(^^)', 'sad' : '(TT)'}
print a['happy']

Invariant and variable

You cannot change parts of the string or tuple later. Reassignment is possible. Data that is no longer referenced is subject to GC.

>>> a = ('p','y','t','h','o','n')
>>> a[0]
'p'
>>> a[0] = 'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

#This is OK
>>> a = ('b','y','t','h','o','n')

Floating point rounding

>>> a = 1.23456
>>> round(a)
1.0
>>> round(a, 1)
1.2
>>> round(a, 4)
1.2346

Getting the base size of an integer (environment dependent)

>>> import sys
>>> print sys.maxint
9223372036854775807
>>> print bin(sys.maxint)
0b111111111111111111111111111111111111111111111111111111111111111
>>> print hex(sys.maxint)
0x7fffffffffffffff

String

Index, slice

>>> a = 'python'
>>> a[0]
'p'
>>> a[-1]
'n'

#You can specify the range of character strings and lists. "Specify by slice"
>>> a[1:3]
'yt'
>>> a[1:]
'ython'
>>> a[:3]
'pyt'

Replace, concatenate, repeat

>>> a = 'python'
>>> a += ' python'
>>> a
'python python'
>>> a.replace('p', 'b')
'bython bython'

#Not destroyed
>>> a
'python python'

>>> b = a * 3
>>> b
'python pythonpython pythonpython python'
>>> a
'python python'

len, find, in

#String length
>>> a = 'python'
>>> len(a)
6

#Existence: use in or find
>>> 'py' in a
True
>>> 'pi' in a
False

>>> a = 'hello python!'
>>> a.find('py', 0, 3) # 0-Does py exist in the third place?
-1
>>> a.find('py', 2) #Returns the index if py exists between the second and the end, if any
6

list

Unlike arrays in other languages, they can have different types

>>> a = [1, 2, 'python', 1.234]
>>> a[0]
1
>>> a[-1]
1.234
>>> a[2]
'python'

Nesting the list

>>> a = [1, 2, [3, 4, 5, 6]]
>>> a[2][2]
5

List slice specification

>>> a = [1, 2, 3, 4]
>>> a[0:2]
[1, 2]

#Naturally it returns as a list even if the number of elements is 1.
>>> a[3:]
[4]

#Swap elements with slices
>>> a[0:2] = [0,0]
>>> a
[0, 0, 3, 4]

#Inserted even if the number of elements is larger than the slice specified range
>>> a[0:2] = [0,0,0,0]
>>> a
[0, 0, 0, 0, 3, 4]

append, extend, del, pop, reverse All destructive methods

>>> a = [0, 1, 2, 3]
>>> a.append(5)
>>> a
[0, 1, 2, 3, 5]

#Use extend to add more than one
>>> a.extend([6,7])
>>> a
[0, 1, 2, 3, 5, 6, 7]

#Delete by specifying an index
>>> del a[2]
>>> a
[0, 1, 3, 5, 6, 7]

#Pop the last element
>>> a.pop()
7
>>> a
[0, 1, 3, 5, 6]

a.reverse()
>>> a
[6, 5, 3, 1, 0]

sort Sort by ASCII

>>> a = [2.4, 1, 'Python', 'A', 3]
>>> a.sort()
>>> a
[1, 2.4, 3, 'A', 'Python']

#In descending order
>>> a.sort(reverse = True)
>>> a
['Python', 'A', 3, 2.4, 1]

Tuple

Parentheses are optional, but should be written for readability. Nested and sliced access is similar to lists

a = ('p','y','t','h','o','n')
>>> a[0]
'p'
>>> a[-1]
'n'
>>> a[0:2]
('p', 'y')
>>> a[:3]
('p', 'y', 't')

#Concatenation and repeat operators are similar to strings
>>> b = ('h', 'e', 'y')
>>> a + b
('p', 'y', 't', 'h', 'o', 'n', 'h', 'e', 'y')
>>> b * 3
('h', 'e', 'y', 'h', 'e', 'y', 'h', 'e', 'y')

Tuple and list conversion

>>> a = (1, 2, 3)
>>> b = list(a)
>>> b
[1, 2, 3]

>>> a = tuple(b)
>>> a
(1, 2, 3)

dictionary

Hash Desune.

>>> a = {'happy' : '(^^)', 'sad' : '(TT)'}
>>> a['happy']
'(^^)'

#Keys with no value return an error, not NULL
>>> a['angry']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0

#Add delete
>>> a['sleepy'] = '(=_=)'
>>> a
{'sad': '(TT)', 'sleepy': '(=_=)', 'happy': '(^^)'}

>>> del a['sad']
>>> a
{'sleepy': '(=_=)', 'happy': '(^^)'}

>>> a.pop('happy')
'(^^)'
>>> a
{'sleepy': '(=_=)'}

String format

% Operator and format () method

>>> a = 10.234
>>> '%d' % a
'10'
>>> '%.2f ' % a
10.23
>>> "%x" % a
'a'
>>> "%s" % a
'10.234'

#When inserting multiple data, pass it as a tuple
>>> a = 7
>>> b = 'python'
>>> msg = '%d wonders of the %s' % (a, b)
>>> msg
'7 wonders of the python'

# '{}'Put the format string in format(variable)
>>> a = python
>>> '{:s}'.format(a) 
'python'

>>> '{}'.format(a)  #No format specified
'python'

>>> a = 10.234
>>> '{:f}'.format(a)
'10.234000'
>>> '{:.2f}'.format(a)
'10.23'

#An error will occur if the format is different
>>> '{:d}'.format(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'float'

#Multiple variables are tuples
>>> b = 4.444
>>> '{:.2f}, {:.3f}'.format(a,b)
'10.23, 4.444'

# {}The method of describing the index as the field name inside is also taken. 0 from the beginning of the argument,1,2,,Becomes
>>> a = "Raspberry Pi"
>>> b = "Python"
>>> c = "in"
>>> '{1} {2} {0}'.format(a,b,c)
'Python in Raspberry Pi'

Null object

None, not NULL or nil

>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nn' is not defined
>>> n = None
>>> n
#Nothing is displayed but it is no longer an error

Recommended Posts

Python basic grammar (miscellaneous)
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Python basic grammar (miscellaneous) Memo (4)
Python3 basic grammar
Python basic grammar / algorithm
Python basic grammar note (4)
Python basic grammar note (3)
Python basic grammar memo
Basic Python 3 grammar (some Python iterations)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Basic Python grammar for beginners
I learned Python basic grammar
Python (Python 3.7.7) installation and basic grammar
Basic grammar of Python3 system (dictionary)
RF Python Basic_01
python grammar check
Basic Python writing
Python grammar notes
RF Python Basic_02
[Basic grammar] Differences between Ruby / Python / PHP
[Python] I personally summarized the basic grammar.
Basic grammar of Python3 system (character string)
Basic grammar of Python3 series (list, tuple)
Basic grammar of Python3 system (included notation)
[Go] Basic grammar ① Definition
Python basic course (12 functions)
Python Basic Course (7 Dictionary)
Python basic course (2 Python installation)
Basic sorting in Python
[Go] Basic grammar ② Statement
Python ~ Grammar speed learning ~
Python basic course (9 iterations)
[python] class basic methods
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Python3 cheat sheet (basic)
Python Basic Course (Introduction)
Python basic memorandum part 2
python basic on windows ②
[Go] Basic grammar ③ Pointer
Python basic memo --Part 2
VBA user tried using Python / R: basic grammar
First Python miscellaneous notes
Python basic course (13 classes)
Basic Python command memo
Basic knowledge of Python
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic course (8 branches)
Python basic if statement
Python Basic Course (3 Python Execution)
Python Basic --Pandas, Numpy-
[For beginners] Learn basic Python grammar for free in 5 hours!
Python application: Pandas Part 1: Basic
Refactoring Learned in Python (Basic)
Grammar features added from Python3.6
BASIC authentication with Python bottle
Python basic dict sort order