Python base python basic data type

Source: Internet
Author: User

This article includes three parts, the first part briefly introduces the basic data types in Python, the second part discusses the common processing methods of numbers, the third part discusses the common processing methods of strings

A. python basic data type                      &NBS P                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp   the basic data types in Python include numbers (int), string (str), list, tuple (tuple), dictionary (dict). One thing to note in Python is that for numbers, unlike other languages there are int and double, all numbers are collectively referred to as Int. There are many built-in methods in Python to handle these basic data types. This article and several subsequent articles will be summed up in the python3 of these built-in methods. The remainder of this article focuses on the built-in methods of numbers and strings.  

Two. How to handle numbers (int)

1.int () function:

1 a='123'2 b=int (a)

the int () function converts a string into a number, and the requirement for a string is that the string is all composed of numbers.

2.bit_length ():

1 a=1232 b=a.bit_length ()3print(b)

The function indicates that a binary representation of the data requires at least several binary numbers.

Three. How to handle strings:

1.capitalize ():

s='hello's.capitalize ()

The capitalize () function is to capitalize the first letter of a string, all other letters in lowercase (note the first letter of the string, not the first letter of the word)

2,casefold () and lower ():

s='hsewaaas's.casefold () s.lower ()

Both of these functions make the string all lowercase, and the two functions differ in that lower can only be used to convert all English letters to lowercase, while cassfold can also convert all letters in other languages (such as French) to lowercase.

3.center (Width,fillchar=none):

1 s='hello'2 s1=s.center (3) s2=s.center (30, ' * ')

The function of the center function is to specify the width of the string and center the string. The function has two parameters the first width represents the width of the string, and the second parameter is a default parameter that specifies what symbol the remaining position of the string is filled with, by default, by a space.

The above-mentioned code performs the following effects:

4.ljust (width,str= ") and Rjust (width,str="):

s='hello's1=s.ljust (*,'*') s2=s.rjust ( "*")print(s1)print(S2)

These two functions are similar to the Ceter function, where ljust means to change the string to the specified width, where the string is left, the remainder is filled with the specified symbol, the default is a space, rjust means that the string becomes the specified width, where the string is right, the other position is populated with the specified character, and the default is a space.

5.count (Sub,start=none,end=none):

1 s='hello Nihaoya'2 s1=s.count ('h')  3 s2=s.count ('h', 6,10)4print (S1) 5 Print (S2)

The function calculates the number of occurrences of the specified string in the target string, which is equivalent to the number of occurrences of the subsequence in the original sequence. Count has three parameters, the first parameter is used to specify the number of substrings to be requested, and the second and third parameters are the default parameters that specify where the original string sequence begins to end. That is, you can either look for the number of occurrences of a subsequence in the entire string, or you can calculate the number of occurrences of a sequence of neutrons in a specified series in a string.

6.endswith (Sub,start=none,end=none), StartsWith (Sub,start=none,end=none):

1 s='hello Nihaoya'2 s1=s.endswith ('ya' )3 s2=s.startswith ('h')4Print  (S1)5print(S2)

These two functions are used to determine whether a string ends and begins with the specified subsequence. Both functions have three parameters, the first parameter is used to specify the subsequence, and the second and third parameters are the default parameters that specify where the original string sequence begins to end. Returns true if the specified sequence ends or starts, otherwise false.

7.expandtabs (width):

s="hell\tdhehde\ndhienwden\tndiwen\n"s1=s.expandtabs (print) (S1)

Code Execution Effect:

The function is to extend the string before each tab key to the specified width. The function allows the string to be output as if it were a table.

8.find (Sub,start=none,end=none), Index (Sub,start=none,end=none):

s="hell\tdhehde\ndhienwden\tndiwen\n"S1=s.find ('de ' )print(S1)

The Find function finds the position of the first occurrence of the specified subsequence in the target sequence, and returns 1 if there is no subsequence in the target sequence. The first parameter of the function is a subsequence that needs to be looked up, and the second and third parameters are the default parameters that specify the starting and ending positions of the original sequence. The index function is consistent with the use of the Find function, but unlike the Find function, where no subsequence returns 1, if Index does not find a subsequence, it will directly error. It is therefore not recommended to use this function.

9.format (), Format_map ():

s='your {name},age{age}'s1=s.format (name='ahah', age=19)print(S1)

The format () function formats the contents of a placeholder in a string. In the string, the {key} is used to represent the placeholder, and the Foramt function allows you to format the contents of the placeholder as a specified content. The Foramt_map () function functions the same as the format function, except that the FORMAT_MAP function can pass in a dictionary. Format is not.

10.isalnum (),

s='123dsds'print(S.isalnum ())

This function is used to determine if the string contains only letters (Chinese) and numbers, if yes, returns true, otherwise false

11.isalpha ():

This function is used to determine if the string contains only letters (Chinese), if yes, returns true, otherwise false

12.isdecimal (), IsDigit (), IsNumeric ():

These three functions are used to determine whether the input string contains only numbers, but the validation range of the three functions is inconsistent, the isdecimal () function can only judge whether it is a normal number (natural number), the IsDigit () function, in addition to the ability to verify the natural number, but also to verify some special numbers, such as the number of ②. IsNumeric () can also verify Chinese characters such as two.

13.isprintable ():

s='123\tsdsds'print(s.isprintable ())

This function determines whether the characters in the string can all be printed, that is, if there are special characters such as \t,\n in the string. If present, it means that the string cannot print it all, the function returns False, and true if all characters in the string can be printed.

14.isspace ():

The function determines whether the given string is all spaces, and if so, returns true, otherwise false

15.istitle (), Tltle ():

Istitle () determines whether the given string is a caption, that is, if the first letter of each word is uppercase, and if so, returns True, otherwise the return False.tilte () function converts the string to a header format.

16.join (s):

s='Hello World's1='_'. Join (s)print (S1)

Code Execution Results:

The join function can be used to delimit strings by inserting the specified characters into the string.

17.islower (), Lower,isupper (), Upper ():

These functions are used to determine whether the strings are all case-sensitive and to convert the strings to uppercase and lowercase.

18.strip (St=none), Lstrip (St=node), Rstrip (St=none)

s='xa's.strip ('91exxe') s.lstrip ('  91exxe') s.rstrip ('91exxe')

These functions are stripped of the characters specified in the string, where strip is either matched from the left or right, lstrip from the left, and Rstrip from the right. The function can set parameters to specify a matching sequence of characters, by default removing spaces (including \t\n).

19.maketrans (STR1,STR2), translate (str):

1 M=str.maketrans ("aeiou","12345")2 v="axbduewbidbw9triuebcqyeeqicbwq"3 new_v=v.translate (m)  4print(new_v)

Naketrans (STR1,STR2) is used to create a correspondence between strings, which is typically used in conjunction with translate (str) functions. The argument to the translate (str) function is the corresponding relationship created by the Maketrans (STR1,STR2) function, and in the Translate function, the corresponding relationship is used for the conversion, that is, the characters in str1 appear in the string. The translate function will then be converted to the corresponding character in the str2. It is important to note that the lengths of str1 and str2 must be consistent to convert.

20.partition (str), rpartition (str)

1 s='testadsddfg'2 v=s.partition ('s' ) )3print(v)4 s1=s.rpartition ('s' ) )5print(S1)

Code effects:

These two functions divide the string into three parts, separated by STR to separate partition (STR) from the first position of the string to find the character str, if the first character str is found, then the character as a separator, the first part of the character as the front, Str as the second section, after the content as the third part, Rpartition is to start from the last position of the string, find the first character str, and then according to STR as a delimiter, the string is divided into 3 parts. If the traversal string has no character str, the three parts returned from the function include the string itself and two spaces.

21.split (str, int.), Rsplit (Str,int)

s='testadsddfg'v=s.split ('s', 2)  Print(v)

The function is a specified number of separators. The partition function will find the first occurrence of the STR character to stop, but split will search the string for int str based on the int value, and then separate the strings according to these str. If the entire string of STR occurrences is less than int, it is delimited by the maximum number of times that STR appears. Similarly, rsplit () is searched forward from the end of the string.

22.splitlines (BOOL)

1 v1=s.splitlines (False)2 v2=s.splitlines (True)3print( V1)4print(v2)

Code Execution Results:

The string is delimited according to \ n, if the argument is false, the \ n is removed and \ n is preserved if the argument is true.

23.swapcase ():

1 s='Hello'2 s1=s.swapcase ()3  Print(S1)

This function is used to convert the case of a string, to lowercase uppercase in a string, and lowercase to uppercase.

24.isidentifier ():

s='def's1=s.isidentifier ()print(S1)

Determines whether a string conforms to a variable naming convention or whether the string is a python keyword. Returns true if a naming convention or keyword is met, otherwise false.

25.replace (Str1,str2,int=node):

1s="Alexalexalexalex"2S1=s.replace ('ex','BBB')3S2=s.replace ('ex','BBB', 2)4 Print(S1)5 Print(S2)

The function replaces the str1 sequence in a string with STR2, by default replacing all str1 sequences, but you can specify the number of substitutions by adding parameters.

Python base python basic data type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.