Python data type-string common operations, python Data Type
This section describes common string operations and examples.
1. python string
There are three methods to declare a string in python: adding single quotation marks, double quotation marks, or three quotation marks on both sides of the string, as shown below:
name = 'hello'name1 = "hello bei jing "name2 = '''hello shang hai haha'''
Once declared, the strings in python cannot be changed as follows:
# The string is an immutable variable, that is, the content name = 'hello' name [0] = 'K' cannot be changed by assigning a value to a position. # The value of the string can be changed by subscript, error message: TypeError: 'str' object does not support item assignment
Common built-in methods for python strings:
In method:
# In method: Determine whether the content exists in the string name = 'Hello bei jing zao an 'print ('hello' in name) # determine whether "hello" exists in name, the execution result is Trueprint ('shanghai' in name) # Check whether the shanghai exists in the name. The execution result is False.
Not method:
Name = 'Hello bei jing zao anc' # define the string # not method: return the 'reverse value' of the expression result '. If the expression result is true, Falseprint ('hello' not in name) is returned. # If hello does not exist in name, the execution result is Falseprint ('abc' not in name) # determine if abc does not exist in name and the execution result is True
Is method:
# Is determines whether the memory address is the same. a = 'xiaoming' B = 'xiaoming' print (a is B) # When the values of a and B are the same, the memory address pointed to is the same, and the result is Trueprint (id (a) print (id (B) # You can view the memory address of the variable through id (variable name ).
The string value operation method is as follows:
Names = 'Hello bei jing one day' print (names [0: 10]) #1. values can be taken by subscript, slice, and head without tail. The execution result is: hello beifor name in names: print (name) #2. through the for loop value, each element in the loop object (names) for k in range (len (names): print (names [k]) #3. the length of the loop names. The value of k is a number, which is equivalent to the subscript of a string.
The endswith, isalnum, and isalpha methods of the string:
Name = 'Hello world is world' print (name. endswith ('D') # judge whether to end with u and the execution result is a Boolean value. In the example, you can determine whether the image ends with jpg print ('ab123 '. isalnum () # when determining whether the input string contains digits and letters and whether the password contains digits and letters, it can be used. The returned result is a Boolean value of print ('abcda '. isalpha () # determines whether the input string is an English letter and returns a Boolean value.
Determine whether the input string is a number, as shown in the following code:
Name = 'abcerf123' print ('20140901'. isdigit () # judge whether the input string is a number. The returned result is a Boolean value.
Remove the space of the string as follows:
# Remove space print ('AB fs '. lstrip () # removes spaces and line breaks on the left of the string by default. Execution result: AB fsprint ('hello '. rstrip () # removes spaces and line breaks on the right of the string by default. The execution result is helloprint ('\ nmysql abcd '. strip () # by default, the spaces and line breaks on both sides are removed. The execution result is mysql abcd. print ('mysqlmy') cannot be removed for spaces in the middle '. strip ('M') # Remove the specified string, for example, remove the m elements on both sides. Execution result: ysqlm y
The string join method is as follows:
# Join is used to concatenate each element of an iteratable object through a string ---> join (parameter type of the iteratable object) print ('*'. join (name) # connect each element in the string with the "*" sign. Execution result: a * B * c * d * E * R * F * 1*2*3, return a new variable value print ('name: ', name after splicing with the asterisk (*) # The content of the name string has not been changed. Execution result: abcdERF123nums = ['ybq', 'lhl ', 'lsh'] print (','. join (nums) # convert the list to a string. Each element is connected by a comma. The execution result is: ybq, lhl, lsh # Another method is to convert the list to a string # nums = ['ybq', 'lhl ', 'lsh'] # temp = ''# for I in nums: # temp = temp + I + ',' # The list is converted to a string and the type conversion is forced. The execution result is: ybq, lhl, lsh # print (temp. strip (','))
Replace the string as follows:
St = 'mysql is db mysql mysql' print (st. replace ('mysql', 'oracle ') # replace mysql in the string with oracleprint (st. replace ('mysql', 'oracle ', 1) # You can enter the number of times you want to replace when many elements are replaced.
Search for the find string as follows:
Name = 'Hello world is world' print (name. find ('World') # search for the string index print (name. find ('World', 3, 10) # You can specify the search string range. 3 and 15 are the start and end values, regardless of the end print (name. find ('xxx') # If the searched string does not exist, the returned result is-1 print (name. rfind ('World') # search for a string from the back to the front. The execution result is: 15.
Cut the string spilt, and the returned result type is list, as follows:
# Cut the string. The return type is listname1 = 'zcl, py, zyz, ywq' # cut the string into listname1_list = name1.split (',') # split the string by commas, the returned result is list, and the name1 value has not changed print (name1_list) # The execution result is of the list type: ['zcl ', 'py', 'zyz ', 'ywq'] print (name1.split () # split the string by space. The returned result is a list with only one element. The execution result is ['zcl, py, zyz, ywq']
Print (name1.spilt ('\ n') # split the string by linefeed
Use line breaks to separate strings, which are not commonly used as follows:
Print ('1 + 2 + 3 \ n1 + 3 + 4 '. splitlines () # split by line breaks. The content of each file row is used as an element of the list. The execution result is ['1 + 2 + 3 ', '1 + 3 + 4']
Strings are randomly generated with uppercase and lowercase letters and numbers. The usage is as follows:
Import stringprint (string. ascii_letters + string. digits) # print (string. ascii_letters) # output uppercase and lowercase English letters. Execution result: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZprint (string. ascii_lowercase) # output lowercase English letters. Execution result: abcdefghijklmnopqrstuvwxyzprint (string. ascii_uppercase) # output lowercase English letters. Execution result: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Format String, as follows:
Print (name. format (name = 'byz', age = 18) # print (name. format_map ({'name': 'hangsan ', 'age': 18}) # format the dictionary
A string is not commonly used. For more information, see:
The determination and conversion of uppercase and lowercase letters in a string are as follows:
Name = 'abcerf123' print ('A '. islower () # determines whether the input string is a lowercase letter. The returned result is a Boolean value of print ('asd '. isupper () # determine whether the input string is a capital letter print (name. lower () # converts uppercase letters in the string to lowercase. The result is: abcderf123print (name. upper () # converts lowercase letters in the string to uppercase. The execution result is ABCDERF123print ('abcdef '. swapcase () # reverse case of uppercase and lowercase letters. Execution result: abcDEF
String ing, which can be used for password encryption as follows:
# Ing p = str. maketrans ('abcdefg', '000000') # map the preceding string to the following string. a --> 1, c --> 3 print ('ccaegg '. translate (p) # The output result is the mapped string according to the above maketrans. The execution result is: 331577 # reverse ing new_p = str. translate ('201312', 'abcdefg') print ('ccaegg '. translate (new_p) # The output result is the ing string based on the above maketrans, And the execution result is: ccaegg
Uppercase of the first letter of a string
Name = 'Hello world is world' print (name. capitalize () # The first letter is capitalized and the execution result is Hello worldprint (name. center (50, '*') # The total length is 50. Place the name string value in the middle and add the * sign on both sides.
Thank you for your attention ~~~