Python Study Notes (3) -- strings

Source: Internet
Author: User
Tags print format string methods translate function

String operation

Strings are a key point in any language. They can be used flexibly to implement various powerful functions. In python, strings are also the case. standard sequence operations are also used for strings, but not for sharding assignment, because the string is unchangeable.

String formatting:

String formatting is implemented using the string formatting operator %. Put a string on the left side of % and the value to be formatted on the right side. Let's look at the following simple example:

>>> format="Hello,%s,I'm studying %s!">>> values=('world','Python')>>> print format % valuesHello,world,I'm studying Python!

Note: If you use a list or other lists instead of tuples, the sequence will be interpreted as a value. Only the tuples, tokens, and more than one value can be formatted.

% S indicates the position where the conversion value needs to be inserted. s indicates that the value will be converted to a string. If it is not a string, STR will be used to convert it to a string. In addition, if you want to include the percent sign in the formatted string, you must use %.

If you need to format the real number, use the f operator type and provide the precision. A data point is added with the number of decimal places you want to save. Because the formatting specifiers always end with a type character, the precision should be placed before the type character:

>>> format="PI with three decimals :%.3f">>> from math import pi>>> print format % piPI with three decimals :3.142

The right operand of the formatting operator can be anything. If it is a tuples or ing type (dictionary), the formatting of the string is slightly different. For example, if the right operand is a tuples, each of the I elements is formatted separately, and each value requires a corresponding conversion specifier. (Note: If the tuples to be converted exist as part of the conversion representation, they must be enclosed in parentheses)

>>> '%s plus %s equals %s ' %(1,1,2)'1 plus 1 equals 2 '

Of course, there are many other character string formatting methods, such as filling, width, and accuracy. It is not too late to use these methods. The following is a comprehensive example of string formatting, including width and alignment:

width=input('Please input width:')price_width=10item_width=width-price_widthheader_format='%-*s%*s'format ='%-*s%*.2f'print '=' * widthprint header_format % (item_width,'Item',price_width ,'Price')print '-' * widthprint format % (item_width ,'Apples',price_width ,0.4)print format % (item_width ,'Pears',price_width ,0.5)print format % (item_width ,'Cantaloupes',price_width ,1.92)print format % (item_width ,'Dried Apricots(16 oz.)',price_width ,8)print format % (item_width ,'Prunes(4 lbs.)',price_width ,12)print '=' * widthraw_input("enter any key to exit~~")

The running result is as follows:

 String method:

Almost every language has many string methods, but they are similar. The idea of string methods in python is very similar to that of data structures.

Find -- search for a substring in a long string and return the leftmost index of the position. Below are common usage:

>>> "Hello, Python, I like Python ". find ('python') # returns the first 'python' index 6 >>> Title = "hahha, hekko, hello" >>> title. find ('Find ') # Return-1-1 >>> subject =' $ get rich now !!! $ '>>> Subject. find ('$') # returns 0> subject. find ('$', 1) # specify the start search position 20 >>> subject. find ('$',) # specify the upper and lower limits of the search. Note that online search does not include offline 0.

Join -- used to add elements (must be strings) to the queue. It is a inverse method of the split method and is very common. The following examples are common usage:

>>> Digitals = [1, 3, 4, 5] >>> seperaor = '+' >>> seperaor. join (digitals) # traceback (most recent call last): file "<pyshell #9>", line 1, in <module> seperaor. join (digitals) typeerror: sequence Item 0: Expected string, int found >>> digitals = ['1', '2', '3', '4 ', '5'] # change to a string >>> seperaor = '+' >>> seperaor. join (digitals) # The list of connected strings is '1 + 2 + 3 + 4 + 5'> dir = '', 'usr', 'bin ', 'env'> '/'. join (DIR) # directory format in Linux '/usr/bin/env'> Print 'C:' + '\\'. join (DIR) # directory format in windows. Note that the backslash must be escaped c: \ USR \ bin \ Env.

Lower -- Return lowercase letters of the string. For program friendliness, sometimes the case sensitivity of user input needs to be "ignored". A unified format should be used for identification in the program. The following describes common usage: (upper is similar)

>>> 'Trouble is a friend! '. Lower ()' trouble is a friend! '>>> If 'jzhou' in ['jason', 'James ', 'jzhou']: # print 'found it is not matched when no conversion is made! '>>> Name = 'jzhou' >>> names = ['jason ', 'James', 'jzhou '] >>> if name. lower () in names: # convert to lowercase to match print 'found it! 'Found it! >>>

The title method and the capwords function of the string module can uppercase the first letter of a sentence, in line with the title habits (improper processing of the title)

>>> 'i like python'.title ()'I Like Python'>>> import string>>> string.capwords ("i like python!")'I Like Python!'>>> 

Replace -- returns the string obtained after all matching items of the string are replaced.

>>> 'This is a test'. Replace ('test', 'work') 'This is a work' # Find and replace

Split: splits strings into sequences. It is the inverse join method and is very commonly used.

>>> '1 + 2 + 3 + 4 + 5 '. split ('+') ['1', '2', '3', '4', '5']> '/usr/bin/env '. split ('/') ['', 'usr', 'bin', 'env']> 'Using the default '. split () # If no separator is provided, all spaces (including spaces, tabs, line breaks, and so on) are used as separators ['using', ''the, 'default'] by default.

Strip (lstrip, rstrip) -- returns a string of spaces on both sides (excluding internal spaces), similar to the trim function (ltrim, rtrim) in C)

>>> 'Internal whtiespace is kept '. strip () 'internal whtiespace is kept '# the leading and trailing spaces are retrieved by default >>> names = ['jason', 'James ', 'jzhou'] >>> name = 'jzhou' # There are two leading spaces >>> if name in names: Print 'found it! '# Mismatch >>> if name. Strip () in names: Print 'found it! '# Retrieve the space and match it with found! >>> '****!! Spam ** for ** everyone !! * ****** '. Strip ('*! ') # Specify the character 'spam ** for ** everyun'>

Translate -- like the replace method, some parts of the string can be replaced, but unlike replace, it only processes a single character, but can be replaced at the same time, sometimes more efficient than replace.

Before using the translate function, you must complete a conversion table. The conversion table corresponds to a certain character. The table has up to 256 Items and can be obtained using the maketrans function in the string module.

The maketrans function has two parameters: two equal-length strings, indicating that each character in the first string is replaced by a character in the same position in the second string, as shown in the following example:

>>> From string import maketrans >>> table = maketrans ('cs ', 'kz') # Replace character C in table with K, replace character s with Z >>> Len (table) 256 >>>> table [97: 123] # extract the processed lowercase letter, the characters C and S have been replaced by 'abkdefghijklmnopqrztuvwxy'> maketrans ('','') [97: 123] # This is an empty conversion (that is, before conversion) 'abcdefghijklmnopqrstuvwxy'>

After the table is created, it can be used as a parameter of the translate method to convert strings as follows:

>>> 'this is an incredibele test'.translate(table)'thiz iz an inkredibele tezt'

The second parameter of translate is optional. this parameter is used to specify the characters to be deleted. For example, you can delete 'fuck' in a sentence:

>>> 'Success, fuck is not a good word '. translate (table, 'fuck') 'tables, iz not a good word' >>> 'tables, fuck is not a good word '. translate (table, '') # delete all spaces 'partition, fukiznotagoodword'

There are many string methods. These methods are commonly used and can be used for query.



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: 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.