Python data type-string common operations

Source: Internet
Author: User
Tags uppercase letter

This time, we mainly introduce the methods and examples of string common operation

1.python string

To declare a string in Python, there are usually three ways to add a single quotation mark, double quotation mark, or triple quotation mark on either side of it, as follows:

' Hello '  " " ' Hello shang hai haha '

Once the string in Python is declared, it cannot be changed, as follows:

# The string is an immutable variable, that is, you cannot change the content by re-assigning a value to a location ' Hello '  'k'# by subscript to modify the value of the string, error message: TypeError: ' str ' object does not support Item Assignment

Python string is a common built-in method for manipulating strings, as follows:

In method:

# in method: Determine whether the content exists in the string '  'print('hello' in name)   #  Determine if hello exists in name, execution result is trueprint('in# determine if Shanghai exists in name, execution result is false

Not method:

Name ='Hello bei Jing Zao an' #Defining Strings#Not method: Returns the ' opposite value ' of an expression result. Returns false if the expression result is truePrint('Hello'  not inchName#Judging Hello does not exist in name, execution result is falsePrint('ABC'  not inchName#To determine that ABC does not exist in name, the execution result is true

Is method:

# is to determine if the memory address is the same ' xiaoming '  'xiaoming'print is b)  #A and B are the same values, Memory, point to the same memory address, point to the result is trueprint(ID (a))print(ID (b))  # The memory address of the variable can be viewed by this method of ID (variable name)

The string value operation method is as follows:

' Hello bei jing one day ' Print (Names[0:10])  # 1. Can be evaluated by subscript, Slice, gu head does not contain tail, the execution result is: Hello bei  for inch names:     Print (name)      # 2. With a For loop value, loop through each element of the Loop object (names)  for inch Range (len (names)):     Print (Names[k])  # 3. The length of the loop names, and the value of K is the number, which is equivalent to the subscript of the string

EndsWith, Isalnum, Isalpha Methods for strings:

 name =  " hello World was world   " print  (Name.endswith ( d   ')  #   to determine whether to end with U, execute the result as a Boolean, working example: You can tell if the picture ends in JPG  print  ( " ab123  "  . Isalnum ()) #   Determines whether the input string contains numbers and letters, determines whether the password contains numbers and letters, Can be used to return a result to a Boolean  print  ( " abcda   ". Isalpha ()) #   

Determines whether the input string is a number, as follows:

' abcdERF123 ' Print ('123'. IsDigit ())  # determines whether the input string is a number, and returns the result as a Boolean value

Remove the whitespace from the string, as follows:

#Remove SpacesPrint('AB FS'. Lstrip ())#by default, the left space and line wrapping of the string are removed, and the result: AB FSPrint('Hello'. Rstrip ())#The default is to remove the whitespace and line breaks to the right of the string and execute the result: HelloPrint('\nmysql ABCD'. Strip ())#The default is to remove both sides of the space and line, the result: MySQL ABCD, the middle of the space can not be removedPrint('Mysqlmy'. Strip ('m'))#removes the specified string, for example: Remove the M element on both sides, and execute the result: Ysqlm y

The Join method of the string, as follows:

#join is used to stitch each element of an iterative object through a string--->join (can iterate over object parameter types)Print('*'. Join (name))#concatenate each element in the string with the * sign, executing the result: a*b*c*d*e*r*f*1*2*3, returning a new variable valuePrint('Use the * number after stitching the name value:', name)#the contents of the name string have not been changed, the result of the execution: abcdERF123Nums = ['YBQ','Lhl','LSH']Print(','. Join (Nums))#converts the list to a string, using a comma connection between each element, and executes the result: Ybq,lhl,lsh#another way to convert a list to a string#nums = [' Ybq ', ' lhl ', ' LSH ']#temp = '#For i in Nums:#temp = temp+i+ ', ' #列表转换为字符串, coercion type conversion, execution result is: Ybq,lhl,lsh#Print (Temp.strip (', '))

Replace the Replace string, as follows:

' MySQL is db mysql MySQL ' Print (St.replace ('mysql'oracle'))    # replace MySQL in a string with Oracle Print (St.replace ('mysql'oracle', 1))   # You can enter the number of times you want to replace a replacement element when there are more

Look for the Find string, as follows:

Name ='Hello World was world'Print(Name.find (' World'))#find the index of a stringPrint(Name.find (' World', 3, 10))#You can specify the range of the lookup string, 3,15 is the start, end subscript value, and the subscript value Gu Tou regardless of the tailPrint(Name.find ('XXX'))#The returned result is 1 when the found string does not existPrint(Name.rfind (' World'))#find the string and look it up from the back and execute the result:

Cut the string spilt, return the result type to list, as follows:

# to cut a string, the returned type is List ' Zcl,py,zyz,ywq '  # cut the string into listname1_list = Name1.split (',')  # to divide the string by commas, The return result for the value of list,name1 does not change the print(name1_list)     # execution result to the list type: [' zcl ', ' py ', ' zyz ', ' Ywq ']print(Name1.split ())  # splits a string by a space, returns a list with only one element, executes the result: [' Zcl,py,zyz, Ywq ']
Print (name1.spilt (' \ n ')) #按照换行符分割字符串

Splitting a string by line break is not commonly used, as follows:

Print ('1+2+3\n1+3+4'. Splitlines ())   # split by line break, splitting the contents of each line of the file as an element of the list, executing the result: [' 1+2+3 ', ' 1+3+4 ']

The string randomly generates uppercase and lowercase letters, numbers, and uses the following:

Import   stringprint(string.ascii_letters + string.digits)  # output all uppercase and lowercase letters + (0-9) digits Print (string.ascii_letters)   # output case of the English alphabet, execution result: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz Print # Output lowercase English letter, execution result: abcdefghijklmnopqrstuvwxyz Print (string.ascii_uppercase)  # Output lowercase English letter, execution result: abcdefghijklmnopqrstuvwxyz

format string, as follows:

Print (The Name.format (name='byz'# formatted string displays print(Name.format_map ({ ' name ' ' Zhangsan ' '  Age ' # Formatting Dictionaries

Methods that are not commonly used in strings, you can understand:

The judgment and conversion of uppercase and lowercase letters in a string are as follows:

Name ='abcdERF123'Print('AA'. Islower ())#determines whether the input string is a lowercase letter, and returns the result as a Boolean valuePrint('ASD'. Isupper ())#determines whether the input string is an uppercase letterPrint(Name.lower ())#turns the uppercase letters in a string into lowercase, executing the result: abcderf123Print(Name.upper ())#capitalize the lowercase letters in the string to execute the result: ABCDERF123Print('ABCdef'. Swapcase ())#uppercase and lowercase letters reversed, execution result: AbcDEF

The mapping of strings can be used for password encryption, as follows:

#Mappingp = Str.maketrans ('ABCDEFG','1234567')#The preceding string and the following string are mapped, a-->1,c-->3Print('Ccaegg'. Translate (p))#The output is mapped to the above Maketrans string, and the result is: 331577#Anti-Solution mappingNew_p = Str.translate ('1234567','ABCDEFG')Print('Ccaegg'. Translate (new_p))#The output is mapped to the above Maketrans string, and the result is: Ccaegg

Capitalize the first letter of a string

' Hello World was world ' Print (Name.capitalize ())  # capitalize first letter, execution result: Hello World Print ' * ' # With a total length of 50, the value of the name string is placed in the middle, and both sides complement the * number display

Welcome to Daniel to supplement ~ ~ ~

Python data type-string common operations

Related Article

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.