程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python | Python basic data types -- numbers, strings

編輯:Python

Catalog

 

python Numbers

1. integer

Digit base and base conversion

Numerical operation

2. floating-point

float And decimal

3. The plural

character string string

Common escape characters

String basic operation

1. String values

2. String concatenation

3. Operation of string

4. String conversion

5.Python String common methods

6.Python String splicing

7. String formatting


python Numbers

python There are three types of numbers : integer , floating-point , The plural

Built in type() Function can be used to query the object type of variable .

1. integer

python2   vs  python3
python2 The integer is divided into : Long integer (long) And integers
python3 Only integers

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

It can also be used isinstance To judge :

>>> a = 111
>>> isinstance(a, int)
True
>>>

isinstance and type The difference is that :

  • type() A subclass is not considered a superclass type .
  • isinstance() Think of a subclass as a superclass type .

Be careful :Python3 in ,bool yes int Subclasses of ,True and False Can be added to numbers , True==1、False==0  Returns the  True, But it can go through  is  To judge the type .

>>> issubclass(bool, int)
True
>>> True==1
True
>>> False==0
True
>>> True+1
2
>>> False+1
1
>>> 1 is True
False
>>> 0 is False
False

stay Python2 There is no Boolean in , It uses numbers 0 Express False, use 1 Express True.

Digit base and base conversion

 

Hexadecimal conversion -bin: Arbitrary binary conversion 2 Base number , Receive one int, Return to one str

>>> bin(10)
'0b1010'
>>> bin(0b11111)
'0b11111'
>>> type(bin(10))
<class 'str'>
>>> bin(0o34)
'0b11100'

Hexadecimal conversion -oct: Arbitrary binary conversion 8 Base number , Receive one int, Return to one str

>>> oct(54)
'0o66'
>>> oct(0b11111)
'0o37'
>>> type(0b11111)
<class 'int'>

Hexadecimal conversion -hex: Arbitrary binary conversion 16 Base number , Receive one int, Return to one str

>>> hex(54)
'0x36'
>>> hex(0o54)
'0x2c'
>>> type(hex(0o54))
<class 'str'>

Hexadecimal conversion -int: Arbitrary binary conversion 10 Base number , Receive one int/str, Return to one int

>>> int(0b11)
3
>>> type(int(0b11))
<class 'int'>
>>> int('1111')
1111
>>> int('0b11',base=2) #base=2 Description the input string is binary
3

Numerical operation

>>> 5 + 4 # Add
9
>>> 4.3 - 2 # Subtraction
2.3
>>> 3 * 7 # Multiplication
21
>>> 2 / 4 # division , Get a floating point number
0.5
>>> 2 // 4 # division , Get an integer
0
>>> 17 % 3 # Remainder
2
>>> 2 ** 5 # chengfang
32

Be careful :

  • 1、Python Multiple variables can be assigned at the same time , Such as a, b = 1, 2.
  • 2、 A variable can be assigned to different types of objects .
  • 3、 The division of a number consists of two operators :/  Returns a floating point number ,//  Returns an integer .
  • 4、 In mixed calculation ,Python Will convert integer to floating point .

2. floating-point

Floating point data type , It can be abbreviated to floating point type .

Decimals are usually stored as floating point numbers , stay Python of use  float  Express .

It can be understood that floating point numbers are used to describe decimals .

float And decimal

float It's not accurate ,float Type can only be reserved after the decimal point 16 position

>>> i=1
>>> i=i-0.1
>>> i
0.9
>>> i=i-0.1
>>> i
0.8
>>> i=i-0.1
>>> i
0.7000000000000001

Decimal Type data is an exact decimal , Can be passed to Decimal Integer or string parameters

from decimal import Decimal
mydec = Decimal("3.22")
print(mydec, type(mydec))
mydec2 = Decimal(3.22)
print(mydec2)
3.22 <class 'decimal.Decimal'>
3.220000000000000195399252334027551114559173583984375

3. The plural

Python It also supports the plural , The plural consists of the real part and the imaginary part , It can be used a + bj, perhaps complex(a,b) Express , The real part of a complex number a Deficiency part of harmony b It's all floating point

>>> a = -5 + 4j
>>> type(a)
<class 'complex'>

character string string

Python Use single quotes for strings in  '  Or double quotes  " Or use three quotation marks (''' or ”””) Cover up , Use the backslash at the same time  \  Escapes special characters .

a = "abc" # Define string
print(a)
#r sign Is to output the original string , No escape
b = r"a\nb"
print(b)
print("a\\nb")
print("\ta\"b")
r sign Is to output the original string , No escape ;raw Function : Return to the original ( Native ) The characters of , That is, do not make escape characters , Output the characters as is , Give Way \t Loss of representation tab Key function

Common escape characters

Escape character is a special character constant . Escape character with backslash "\" start , Followed by one or more characters . Escape characters have It has a specific meaning , Different from the original meaning of characters , Therefore calls “ escape ” character .

\( When at the tail )    Line continuation operator

\n Line break

\\ Backslash notation

\' Single quotation marks

\t Horizontal tabs

\" Double quotes

\r enter

String basic operation

# An immutable sequence of strings
# Once you create a string , You can't change it any more .

1. String values

  1. Subscript value method ( Be careful : Subscript from 0 Start )
  2. Slice method
>>> a='abcdefghijklmn' Each character corresponds to an index ( Subscript ), Number from 0 Start
0123456789
>>> print(a[-8]) Eighth from right to left
g
>>> a[5] Fifth from left to right
'f'
>>> a[3:6] From left to right 3 To 6 individual , The sixth one is not included , Left closed right open interval
'def'
# The format is a[start:end:step] step The default is +1,step Being positive , Cut step from left to right
# step Negative , Cut step from right to left
>>> a[8:2:-2]
'ige'
# String slice index
# str[start:end:step]
# str1='abcdefghijk'
# 1, Determines whether the step size is positive or negative
# Being positive Value from left to right
# Negative Value from right to left
# 2, Determine the starting position
#3, Determine the step size
print(str1[-9:8:2]
print(str1[2:]) #end Value is empty , Contains the last number
print(str1[:7]) #end The value is not empty. , Not including the last number
print(str1[::-1]) # Flashback the entire string 

2. String concatenation

>>>str2 = "aa""bbb"
>>>print(str2)
'aabbb'

3. Operation of string

>>>str3 = "hello,"
>>>str4 = "world!"
>>>print(str3 + str4)
>>>print(str3*3)
'hello,world!'
'hello,hello,hello,'

4. String conversion

>>>result = str(100)
>>>print(type(result), result)
<class 'str'> 100

5.Python String common methods

1. Judgement series

str.isdigit() Whether the string contains only numbers

str.isnumeric() Whether the string contains only numbers ( Including Chinese one to nine )

str.isalnum() Whether the string contains only letters or numbers

str.istitle() Whether the first letter of each word in the string is capitalized , Other letters are lowercase

str.isalpha() Whether the string contains only letters ( Chinese characters count as letters )

str.isupper() Whether the string is all uppercase

str.isidentifier() Whether the string is a legal identifier

str.isprintable() Whether the string is a printable character

str.islower() Whether the string is all lowercase

str.isspace() Whether the string contains only spaces (tab It's also a blank space )

str.startswith(prefix[, start[, end]]) Whether a string starts with a string , Can pass start and stop Parameter setting Set the search scope

str.endswith(suffix[, start[, end]]) Whether the string ends with a string , Can pass start and stop Parameters Set the search scope

>>> str='abc123'
>>> str.isidentifier()
True
>>> str.isprintable()
True
>>> str.isspace()
False
>>> str.startswith('a',0,4)
True
>>> str.endswith('a',0,4)
False
>>> str.isdigit()
False
>>> str.isnumeric()
False
>>> str.isalnum()
True
>>> str.istitle()
False
>>> str.isalpha()
False
>>> str.islower()
True
>>> str.isupper()
False

2. Find statistics class

len(string) Statistical string length

str.count(sub [,start [,end]]) Statistics substring Number of occurrences in the string

str.index(sub [,start [,end]]) Show substring The first subscript position in the string , No mistake

str.find(sub [,start [,end]]) lookup substring, Find and return to its starting position , No return found -1

# See how many times a character appears
>>> 'helloworld'.count('l')
3
# Count the length of the string
>>> len('klajfdla')
8
# Check the subscript where a letter first appears
# If it doesn't, report it wrong , An error will terminate the program , It is not recommended to use
>>> 'ajfklas'.index('l')
4
>>> 'ajfklas'.index('g')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
#find If you don't find a letter, you won't report an error , Recommended
>>> 'ajfklas'.find('g')
-1

3. String conversion class ( Return a new object )

str.upper() Convert strings to uppercase

str.lower() Convert string to lowercase

str.title() Capitalize the first letter of a word in a string , Other letters are lowercase

str.split('sep') Appoint 'sep' Cut the string into a list as a separator , The separator can be any character ( Silent Recognize as a space )

'str'.join(list) Use the list as str Splicing into a large string

str.strip([string]) Remove the first and last strings in the string , Without parameters, spaces are removed by default

str.zfill(number) Returns a string of a specified length , Align the original string to the right , Fill in the front 0

str.replace('old', 'new'[, count]) Replace old characters with new characters , You can also specify the number of substitutions , Default all Replace str.capitalize() The first letter of the sentence is capitalized

str.center(width[, fillchar]) ,str.ljust(width[, fillchar]) ,str.rjust(width[, fillchar]) Returns an original string centered ( Keep to the left / Keep right ) alignment ,width Is the total length , two Side with a character fillchar fill , If the specified length is less than... Of the original string Length returns the original string .

str.expandtabs(number) take \t convert to number A space

>>> str.upper()
'ABC123'
>>> str.lower()
'abc123'
>>> str.title()
'Abc123'
>>> str.split()
['abc123']
>>> str.split(' ')
['abc123']
>>> str.split('1')
['abc', '23']
>>> a=str.split('1')
>>> '1'.join(a)
'abc123'
>>> str.swapcase()
'ABC123'

6.Python String splicing

1. Directly through (+) Operator splicing :

Using this method to connect strings is inefficient , because python Use in + When two strings are spliced, a new string is generated , To generate a new string, you need to reapply memory , When there are many concatenated strings, the efficiency will be affected .

2. adopt str.join() Method splicing :

This method is often used to convert a set to a string ,''''.join() among '''' It can be an empty character , It can be any other character , When it's any other character , The string in the collection will be separated by this character

3. adopt str.format() Method splicing

To splice strings in this way, you need to pay attention to : In a string {} The quantity should be the same as format The number of method parameters is consistent, otherwise an error will be reported !

4. adopt (%) Operator splicing

In this way str.format() Basically the same way of use

>>> a=' String splicing 1'
>>> b=' String splicing 2'
>>> print(a+b)
String splicing 1 String splicing 2
>>> print("%s %s"%(a,b))
String splicing 1 String splicing 2
>>> print('{},{}'.format(a,b))
String splicing 1, String splicing 2
>>> print(f'{a},{b}')
String splicing 1, String splicing 2
>>> c=f'{a},{b}'
>>> c
' String splicing 1, String splicing 2'

7. String formatting

One 、 Use % Symbols to format

 The basic format
%[(name)][flags][width].[precision]typecode
- (name): name
- flags: +,-,' ' or 0.+ A plus sign for a positive number ;- Indicates left alignment ;' ' For a space , Means to fill an empty space to the left of a positive number
grid , To align with a negative number ,0 Said the use of 0 fill .
- width Indicates the display width
- precision Precision after decimal point
-typecode Represents the data type %s     character string ( use str() Display of )
%r     character string ( use repr() Display of )
%c     Single character
%b     Binary integer
%d     Decimal integer
%i     Decimal integer
%o     Octal integer
%x     Hexadecimal integer
%e     Index ( The base is written as e)
%E     Index ( The base is written as E)
%f     Floating point numbers
%F     Floating point numbers , Same as above
%g     Index (e) Or floating point ( According to display length )
%G     Index (E) Or floating point ( According to display length )
%%     character "%", Show percent sign %
>>> print(" The first format :%10x"%(10))
The first format : a
>>> print(" The second format :%+x"%(10))
The second format :+a
>>> print(" The third format :%06d"%(10))
The third format :000010
>>> print(" The fourth format :%-6d"%(10))
The fourth format :10
>>> print(" The fifth format :%09.3f"%(3.245345))
The fifth format :00003.245
>>> num1 = 0.34539203
>>> print("%.2f%%"%(num1*100))
34.54%
>>>

Two 、 Use .format The format of

Basic usage format  < Template string >.format(< Comma separated parameters >)

 < Template string > Content :{ Variable :[ Fill character ][ Alignment mode <^>][ Width ][,( Kilo format )][ precision ][ Format ]}


s = "PYTHON"
# Filling defaults to blank space
"{0:30}".format(s)
Out[17]: 'PYTHON '
"{0:>30}".format(s)
Out[18]: ' PYTHON'
"{0:*^30}".format(s)
Out[19]: '************PYTHON************'
"{0:-^30}".format(s)
Out[20]: '------------PYTHON------------'
# Refers to the set output character width of the current slot , If the slot corresponds to format() Parameter length ratio < Width > The setting value is large , The actual length of the parameter is used .
# If the actual number of digits of the value is less than the specified width , The number of digits will be supplemented by a space character by default .
"{0:3}".format(s)
Out[21]: 'PYTHON'
#< Format control flag > Middle comma (,) Thousand separator for displaying numbers
"{0:-^20,}".format(1234567890)
Out[24]: '---1,234,567,890----'
"{0:-^20}".format(1234567890) # Compare output
Out[25]: '-----1234567890-----'
"{0:-^20,}".format(12345.67890)
Out[26]: '----12,345.6789-----'
# For floating-point numbers , Precision represents the number of significant digits of the fractional output . For strings , Precision represents the maximum length of the output .
"{0:.2f}".format(12345.67890)
Out[29]: '12345.68'
"{0:H^20.3f}".format(12345.67890)
Out[30]: 'HHHHH12345.679HHHHHH'
"{0:.4}".format("PYTHON")
Out[31]: 'PYTH'

  3、 ... and 、f-string To format a string ——python3.6 above

for example :

# Only python3 Support python2 This is not supported
name = "sc"
age = 4
result = f"my name is {name}, my age is {age:*>10}"
print(result)

  give the result as follows :

my name is sc, my age is *********4


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved