python Foundation: string (with code)

Posted by dreamkiller23 on Wed, 09 Mar 2022 15:37:41 +0100

Write it in the front, Hello everyone! I'm Xlong, an engineering man in a non computer class. Since I have been learning python recently and have taken a lot of notes about python learning, I want to sort out a series of articles about its foundation, which is convenient for my daily review on the one hand, and also want to communicate and learn with many small partners on this platform. I hope that through this sorting, I can have a clearer understanding and understanding of python. If there are deficiencies or mistakes, please correct me in the comment area or private letter. Thank you for your generous advice and thank you very much for your support.
Use knowledge to achieve the future. Let's cheer together ̀ o• ́) ง (ง • ̀ o• ́) ง(ง • ̀ o• ́) ง

Introduction to this article

In the previous chapter Fundamentals of python (8): tuples and sets (with code) In, we introduce many concepts such as tuple and set in detail. In this article, we mainly study strings in python.

catalogue

Introduction to this article

1, String resident mechanism

2, Common operations of string

2.1 query operation method of string

2.2 case conversion method of string

2.3 method of string content alignment

2.4 method of string splitting operation

2.5 method of judging string operation

2.6 other methods of string operation

III. comparison of strings

4, Slicing operation of string

5, Format string

Vi. encoding conversion of string

1, String resident mechanism

1. String: in python, string is a basic data type and an immutable character sequence.

2. String resident mechanism:

(1) The method of saving only one copy of the same and immutable string. Different values are stored in the string resident pool. python's resident mechanism only keeps one copy of the same string. When creating the same string later, it will not open up a new space, but assign the address of the string to the newly created variable

#String resident mechanism
a = 'python'
b = "python"
c = '''python'''
print(a,id(a))  #Output result: python 2713985600368
print(b,id(b))  #Output result: python 2713985600368
print(c,id(c))  #Output result: python 2713985600368

(2) Several cases of resident mechanism (interaction mode)

  • When the length of the string is 0 or 1

  • String matching identifier

  • Strings reside only at compile time, not at run time

  • Integer number between [- 5256]

(3) Advantages and disadvantages of resident mechanism

  • When a string with the same value is needed, it can be directly used from the string pool to avoid frequent creation and destruction, improve efficiency and save memory. Therefore, splicing and modifying strings will affect the performance

  • When string splicing is required, it is recommended to use the str type join method instead of +. Because the join () method first calculates the length of all characters and then copies them. The object is only new once, which is more efficient than "+"

2, Common operations of string

2.1 query operation method of string

2.2 case conversion method of string

s = 'hello,python'
a = s.upper() #After capitalization, a new string object is generated
print(a,id(a))      #Operation result: HELLO,PYTHON 2252801261296
print(s,id(s))      #Operation result: hello,python 2252801362800
b = s.lower()  #After conversion, a new string object is generated
print(s.lower(),id(s.lower()))      #Operation result: hello,python 2252803178608
print(s,id(s))      #Operation result: hello,python 2252801362800
print(b==s)         #Operation result: True
print(b is s) #False operation result: false

s2 = 'hello,Python'
print(s2.swapcase()) #Operation result: HELLO,pYTHON
print(s2.title())    #Operation result: Hello,Python

2.3 method of string content alignment

2.4 method of string splitting operation

2.5 method of judging string operation

To be added

2.6 other methods of string operation

III. comparison of strings

To be added

4, Slicing operation of string

To be added

5, Format string

1. Two ways to format strings

(1) % as placeholder

(2) {} as placeholder

#format string 
#(1) % placeholder
name = 'Zhang San'
age = 20
print('My name is%s,this year%d year'%(name,age))        #Running results: my name is Zhang San, 20 years old
#(2) {} placeholder
print('My name is{0},this year{1}year'.format(name,age))	#Operation result: my name is Zhang San, and I'm 20 years old
#(3)f-string
print(f'My name is{name},this year{age}year')			#Operation result: my name is Zhang San, and I'm 20 years old
print('%10d' %99)  #10 Represents the width                    #Operation result: 99
print('%.3f' % 3.1415926) #.3 Represents three decimal places      #Operation result: 3.142
#Both width and precision
print('%10.3f' %3.1415926) #The total width is 10, with 3 decimal places      #Operation result: 3.142
print('hellohello')										#Running result: hello hello
print('{0:.3}'.format(3.1415926)) #. 3 represents the operation result of three significant digits in total: 3.14
print('{:.3f}'.format(3.1415926)) #. 3f represents the 3-digit decimal operation result: 3.142
print('{:10.3f}'.format(3.1415926)) #Set the width and precision at the same time. There are 10 digits in total, and 3 digits are decimals

Vi. encoding conversion of string

1. Why do you need string encoding conversion

The earliest string encoding is ASCII code, which only includes numbers from 0 to 9, letters of a ~ Z and a ~ Z, and other symbols such as spaces and tabs, with a total of 256 characters. With the development of information technology, the characters of all countries need to be coded, so GBK/GB2312 coding and UTF-8 coding appear.

In Python 3, UTF-8 encoding is adopted by default; In Python, there are two common string types: str and bytes. These two types of strings cannot be used together. If we need to transmit or save to disk on the network, we should perform encoding conversion, that is, str should be converted to binary data (bytes). To do this, you need to use the encode () method.

For more information, please move to Python string encoding conversion.

2. Encoding and decoding methods

(1) Encoding: convert string to binary data (bytes)

(2) Decoding: convert data of bytes type to string type

s = 'The ends of the earth are at this time'
#code
print(s.encode(encoding='GBK'))  #In GBK, one Chinese occupies two bytes
print(s.encode(encoding='UTF-8'))#In the editing format of UTF-8, one Chinese occupies three bytes
#decode
#Byte stands for binary data (data of byte type)
byte = s.encode(encoding='GBK') #code
print(byte.decode(encoding='GBK')) #decode

byte = s.encode(encoding='UTF-8')
print(byte.decode(encoding='UTF-8'))

Unfinished to be continued

Originality is not easy. Please click Follow and Star, thank you!!!

Topics: Python Pycharm