The introduction of
The data stored in memory can be of different data types. For example, names can be stored as strings, ages can be stored as numbers, and Python has six basic data types for storing various types of data: numbers, String, List, Tuple, and Dictionary.
This article introduces numeric and string types.
Number type
Python numeric data types are used to store values, and numeric types are immutable data types.
Python supports three different numeric types:
1. Integer (int), no decimal point, no limit on size, can be used as long, so Python3 does not have long numbers.
2. A float with a decimal point, consisting of an integer part and a decimal part
3. Complex, which consists of real and imaginary parts. For example, a+bj can be represented by complex(a,b). The real part A and imaginary part B of the complex are floating point types. In the actual development of relatively few, except to do industrial design calculations.
How are numeric types defined in Python? Specific methods are as follows:
# Integer and floating point
a = 10
b = 10.2
# the plural
c = complex(1.2)
Copy the code
Numeric types can be converted, but numeric types cannot convert other data types, such as string lists, to numeric types.
"Int (x) converts x to an integer. Float (x) converts x to a floating point number. Complex (x) converts x to a complex number with a real part of x and an imaginary part of 0. Complex (x, y) converts x and y to a complex number with the real part x and the imaginary part y. X and y are numerical expressions. ' ' '
a = 1.0
b = int(a) # transform a into an integer
Copy the code
Mathematical operations can be performed between int and float using numeric operators.
print(2 + 2)
print(10 / 3) Always return a floating-point number. The result may be different on different computers due to accuracy issues
Copy the code
String type (STR)
Strings are the most commonly used data type in Python. Strings are immutable data types created using pairs of single or double quotes.
name = 'python'
gender = "male"
Copy the code
Strings can convert any other type to a string.
res=str({'a':1})
print(res,type(res))
Copy the code
There are many methods for strings. Here are some common methods for strings.
First, get the value of the specified position (index) in the string.
Each character in a string is indexed, with forward indexes starting at 0 and reverse indexes starting at -1, as shown in the following figure
To retrieve a character at a specified position in a string, use an index (either forward or reverse).
my_str = 'python'
# forward value
str1 = my_str[0] # P
str2 = my_str[5] # n
# reverse value
str3 = my_str[-1] # n
str4 = my_str[-6] # P
Copy the code
Second, index extensions — slicing, which accesses substrings of a string, can have square brackets to intercept the string, syntax is as follows
Variable [start index: End index: step size] Note: [] value does not include the end index value, can control the step size of the output substring ""
my_str = 'python'
# Forward section
str1 = my_str[0: 5] # pytho
str2 = my_str[0: 5] # is equivalent to my_str[0:5:1], with a step of 1
str3 = my_str[0: 5: 2] The # step is equal to 2, which is equivalent to taking every other value from the first character, so the result is pto
str4 = my_str[5: 0: -1] # The step size can be negative, indicating that the substring is taken from the reverse order, resulting in nohty
str5 = my_str[:] # means to take all characters in a string, Python
str6 = my_str[::] # means to take all characters in a string, Python
str7 = my_str[::-1] # means to reverse the string, nohtyp
# Reverse slice
str6 = my_str[-1: -3: -1] # no
Copy the code
Third, look at the length of the string – the len method
my_str = 'python'
print(len(my_str)) # 6
Copy the code
Fourth, the member operations in and not in
# in Checks whether hello is in str1
>>> 'hello' in str1
True
# Not in: Check if Tony is not in STR1
>>> 'tony' not in str1
True
Copy the code
Fifth, the for loop, iterates over each character in the string
my_str = 'python'
# string is an iterable, fetching each character in the string in turn
for i in my_str:
print(i)
Copy the code
Sixth, string operations
Strings can operate with each other, but strings cannot operate with other data types
a = hello
b = world
String concatenation operation
print(a + b) # helloworld
# * Repeat the output string
print(a * 2) # hellohello
Copy the code
There are a lot of built-in methods for string types, but they are not used very often. Here are just some of the most commonly used methods, and the other less commonly used methods. I hope you can learn by yourself.
For formatted output of strings, see the previous article, Interaction with users.
Strip () lstrip() rstrip() method: Removes the specified character from the string twice
str1 = '**tony***'
# no characters are specified in parentheses. Whitespace characters, such as the space TAB character, are removed by default
str1.strip(The '*') Removes the specified characters from the left and right sides
str1.lstrip(The '*') # Remove only the specified character on the left
str1.rstrip(The '*') # Remove only the specified character on the right
Copy the code
Split () rsplit() method: splits the string according to the specified characters. The result is a list
# no characters are specified in parentheses, default is space as the split symbol
str3 = 'hello world'
b = str3.split()
print(b) # ['hello', 'world']
# split splits the string from left to right. You can specify the number of splits
str5='C:/a/b/c/d.txt'
print(str5.split('/'.1)) # ['C:', 'a/b/c/d.txt']
# rsplit is the opposite of split, it cuts from right to left, and you can specify the number of cuts
str5='a|b|c'
print(str5.rsplit('|'.1)) # ['a|b', 'c']
Copy the code
Lower () upper() method: Change all strings to lowercase and uppercase
>>> str2 = 'My nAme is tonY! '>>> str2.lower() My name is Tony! >>> str2.upper() # MY NAME IS TONY!
Copy the code
Startswith () endswith() : Determine what string begins and ends, and the result is a Boolean value
>>> str3 = 'tony jam'# startswith() determines if the string begins with the character specified in parentheses, The result should be a Boolean value True or False>>> str3.startsWith ('t') True>>> STR3.startsWith ('j')False# endsWith () Result is Boolean True or False>>> str3.endswith('jam')True>>> str3.endswith(' Tony ') False
Copy the code
Join (): Retrieves multiple elements from an iterable and concatenates them according to the specified concatenate, resulting in a string.
>>> The '%'.join('hello') # from the string 'hello' to retrieve multiple characters, and then according to the % as a connector for Mosaic 'h % % % % e l l o' > > > '|'. Join ([' Tony ', '18', 'read']) # from the list take out more characters, Then according to the | as connector for Mosaic 'Tony 18 | | read'
Copy the code
The replace() method: replaces the old character in the string with a new character, and you can specify the number of changes
>>> str7 = 'my name is tony, my age is 18! ' Str7 = str7.replace('18', '73') # syntax :replace(' old content ', 'new content ')>>> STR7my name is Tony, my age is 73! Str7 = 'My name is Tony, my age is 18! '>>> STR7 = str7.replace('my', 'my', 1) # change a my to my >>> STR7 'My name is Tony, my age is 18! '
Copy the code
Isdigit (): Checks whether the string is composed of pure digits, returning True or False
>>> str8 = '5201314'>>> str8.isdigit()True>>> str8 = '123g123'>>> str8.isdigit()False
Copy the code
center() ljust() rjust() zfill()
>>> name='tony'>>> name.center(30.The '-') # 30, total width of string centered, inadequate filling -- -- -- -- -- -- -- -- -- -- -- -- -- -- Tony -- -- -- -- -- -- -- -- -- -- -- -- -- > > > name, ljust (30, '*') # 30, total width of string left aligned, Inadequate filling Tony * * * * * * * * * * * * * * * * * * * * * * * * * * * > > > name. Rjust (30, '*') # 30, total width of string right alignment, Enough with * * * * * * * * * * * * * * * * * * * * * * * * * * * Tony > > > name. Zfill (50) # total width of 50, string right alignment, Not enough 0000000000000000000000000000000000000000000000 Tony with 0
Copy the code
captalize(),swapcase(),title()
# captalize: capitalized >>> message = 'Hello everyone nice to meet you! '>>> message.capitalize()Hello everyone nice to meet you! Message1 = 'Hi girl, I want to make friends with you! '>>> message1.swapcase() hI GIRL, i WANT MAKE FRIENDS WITH YOU! MSG = 'Dear my friend I miss you very much'>>> MSG. Title ()Dear my friend I miss you very much
Copy the code