character string
A string is a sequence of independent characters
1, There are two methods to convert an object into a string: str() and repr()
(1)repr() Converted to a form for the interpreter to read
(2)str() Into a form suitable for human reading
a = 123456 print('repr Output:', repr(a)) print('str Output:', str(a)) b = "Hello,\nworld" print('repr Output:', repr(b)) print('str Output:', str(b)) Operation results: repr Output: 123456 str Output: 123456 repr Output: 'Hello,\nworld' str Output: Hello, world
2, Long string across lines
You can use the following methods
(1) The string is enclosed in three quotation marks' ', or three double quotation marks''
a = '''Hello, world''' print(a) Operation results: Hello, world
(2) Add a backslash at the end of the line \, The difference between the running result and the above is that the string does not wrap
b = "Hello,\world"print(b) Operation results: Hello,world
(3) If you want to specify to end with a backslash, you need to add 2 more backslashes \
b = "Hello,\\\world"print(b) Operation results: Hello,\world
(4) Original string, prefixed with r
print('c:\now')print(r'c:\now') The operation results are as follows, and the original string will be output as it is: c:owc:\now
(5) The original string cannot be with a single backslash \ End, if you want to specify ending with a backslash, you can use the backslash as a separate string
print(r'c:\now''\\') Operation results: c:\now\
3, Formatting of strings
(1) Use percentage symbol % Indicates that a string is specified on the left of% and the value to be formatted is specified on the right of%.
When specifying a value (such as a string or a number) to format, you can use a single value, tuples, dictionaries, etc.
Several common formatting symbols:
%s format string
%d Format integer
%f Format floating-point numbers to specify the precision after the decimal point
(2) Template string formatting, assignment using keyword parameters
(3) The variable has the same name as the replacement field. You can use the abbreviation and add f before the string
(4) Using the string method format, each replacement character is represented by curly braces {}
1. Unnamed field, direct curly braces
a = "{},{}".format("Hello","world") print(a) Operation results: Hello,world
2. Index
a = "{1},{0}, {1}".format("Hello","world") print(a) Operation results: world,Hello, world
3. Named field
a = "{h},{w}".format(h="Hello", w="world") print(a) Operation results: Hello,world
list
1, Several uses of lists.
(1) . the list can be indexed, and the elements can be retrieved according to the index,
(2) The list can be sliced to take out the sub list. Several uses of the list.
2, List apped Usage of and pop
l = [1,2,3,4,5,6] l.append(2) print(l) s = l.pop() print(s)
3, Usage of index list
l = [1,2,3,4,5,6] s = l.index(3) print(s)
4, List sort and reverse and sorted
d = [3,2,5,6,8,1] l = sorted(d) print(l) d.reverse() d.sort()
5, List Usage of extend
d = [3,2,5,6,8,1] l = [1,2,9,4] d.extend(l) print(d)
Yuanzu
Python tuples are similar to lists, except that elements in tuples cannot be modified (so tuples are also called read-only lists), and tuples use parentheses while lists use brackets
1, When a tuple contains only one element, you need to add a comma after the element to eliminate ambiguity
tup1=(10,)
2, Element values in tuples are not allowed to be modified, but tuples can be connected and combined
tup1=(12,34.56) tup2=('abc','xyz') tup1[0]=100 tup3=tup1+tup2 print(tup3) output:(12,34.56,'abc','xyz')
3, Elements in tuples are not allowed to be deleted, but the del statement can be used to delete the whole tuple
4, Tuples can use + and *, that is, tuples are allowed to be combined, connected and duplicated, and a new tuple will be generated after operation
tup1=(1,2,3) tup2=(3,4,5) tup3=tup1+tup2 tup4=tup1*3 print(tup3) print(tup4) Output: tup3=(1,2,3,3,4,5) Output: tup4=(1,2,3,1,2,3,1,2,3)
5, Tuple run slice operation
6, Any unsigned object, separated by commas, defaults to tuples
a=1,2,3,'hello' print(a) Output:(1,2,3,'hello')
7, A built-in function that operates on tuples
——cmp(tup1,tup2): Compare two tuple elements
——len(tup): Returns the number of elements in a tuple
——max(tup): Returns the maximum value of an element in a tuple
——min(tup): Returns the smallest value of an element in a tuple
——tuple(seq): Convert list to tuple
8, Methods of tuples (tuples do not have the operations of adding, deleting and modifying in the list, but only the operations of querying)
——tuple.index(obj): find the index value of the first match of a value from the tuple
——tuple.count(obj): Counts the number of occurrences of an element in a tuple
Dictionaries
Dictionary is also a common data structure provided by python. It is used to store data with mapping relationship
1, Create Dictionary:
dict={'name':'mike','age':12,'class':'First'} print(dict['name'],dict['age'])
2, Common methods of dictionary
The dictionary is represented by the dict class, so we also use dir (dict) to see which methods this class contains, and enter the dir (dict) command in the interactive interpreter
dir(dict) ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
(1) Here are some methods of dict
clear()
cars = {'BMW':8.5,'BENS':8.3,'AUDI':7.9} cars.clear() print(cars)
get()
Method: in fact, it is to obtain value according to the key. It wants to be in the enhanced version of square brackets. When using square bracket syntax to access a nonexistent key, the dictionary will cause keyError error error; however, if using get() method to access a nonexistent key, the method will simply return None and will not cause an error
cars = {'BMW':8.5,'BENS':8.3,'AUDI':7.9} print(cars.get('BMW')) print(cars.get('dfdefe')) print(cars['dkfjeife'])
update()
Method: you can use the information contained in a dictionary key-value To update the existing dictionary update() Method, if the updated dictionary already contains the corresponding key-value Yes, so the original value Will be overwritten; if the updated dictionary does not contain the corresponding key-value Yes, then key-value To be added.
cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9} cars.update({'BMW':4.5, 'PORSCHE': 9.3}) print(cars)
pop()
Method: used to specify the value corresponding to the key and delete the key value pair
cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9} print(cars.pop('AUDI')) print(cars) Output: 7.9 Output:{'BMW': 8.5, 'BENS': 8.3}