python_04-string manipulation

Source: Internet
Author: User

Directory:

1 operation of the string

1.1 Connection of strings

1.2 Taking a partial string

1.3 Other string-handling functions

1.4 string-handling functions in libraries

1.5 Python's string manipulation function

1.5.1 character-case transformations in strings

1.5.2 the alignment of strings at output

1.5.3 Search and Replace in a string

Mapping of the 1.5.4 string

The 1.5.5 string also has a pair of encoded and decoded functions

1.5.6 String type conversion function

1 operation of the string

Strings are frequently used in the program, strings are also many operations, including the connection of two strings, take a part of a string, called the substring, case conversion, string and numeric conversion, and so on.

1.1 Connection of strings

S0 = "Python"

S1 = ' C + + '

s2=s0+ "" +s1

Print (S0, ' \ n ', s1, ' \ n ', S2)

>>>

Python

C++

Python C + +

S2 The value is: ' Python C + + '

1.2 Taking a partial string

< string name >[< start position >: < stop position >: < step;]

get from < Start position > Start, Interval < Step > , to < End Position > a string that ends with the previous character. Which

< Start position > can be omitted, indicating a starting position of 0 .

< End Position > can be omitted, indicating the end from the terminating position.

< Step > omit indicates a step of 1 .

For example:

f= ' ABCDEFGHIJKLMNOPQRSTUVWXYZ '

The

F[5] the value is ' F '

F[0:10:2] the value is ' Acegi '

F[0:10] the value is ' Abcdefghij '

F[:10] the value is ' Abcdefghij '

f[10:] the value is ' klmnopqrstuvwxyz '

Len (f) # The length of the string, the result of this example is

1.3 Other string-handling functions

Other string handling functions include the following:

Ord (' A ') # returns the ASCII of a character the decimal value

Chr (The) # returns the character corresponding to an integer

1.4 string-handling functions in libraries

the string processing function above can be used directly, but to use the casing conversion, lookup and other functions, you need to introduce a string Library by writing an import string at the beginning of the program ", for example:

Import string

f= ' abcdefghijklmnopqrstuvwxyz ' # Define a string

S1=f.upper () # convert to uppercase, do not change f

Print (S1)

Print (F.find (' F ')) # return F the index value (that is, in the string from 0 number of start)

s2=f.replace (' B ', ' Boy ') # return b by Boy Replace the string, do not change f

Print (s2)

>>>

Abcdefghijklmnopqrstuvwxyz

5

Aboycdefghijklmnopqrstuvwxyz

other string processing functions are shown in table 4-3 .

Table 4-3 String string processing functions in the library

S.capitalize ()

S.ljust (width [, fill])

S.center (width [, fill])

S.lower ()

S.count (Sub [, Start [, end]])

S.lstrip ([chars])

S.encode ([encoding [, errors]])

S.maketrans (x[, y[, z])

S.endswith (suffix [, start [, end]])

S.partition (Sep)

S.expandtabs ([tabsize])

S.replace (old, new [, Count])

S.find (Sub [, Start [, end]])

S.rfind (Sub [, Start [, end]])

S.format (Fmtstr, *args, **kwargs)

S.rindex (Sub [, Start [, end]])

S.index (Sub [, Start [, end]])

S.rjust (width [, fill])

S.isalnum ()

S.rpartition (Sep)

S.isalpha ()

S.rsplit ([sep[, Maxsplit]])

S.isdecimal ()

S.rstrip ([chars])

S.isdigit ()

S.split ([Sep [, Maxsplit]])

S.isidentifier ()

S.splitlines ([keepends])

S.islower ()

S.startswith (prefix [, start [, end]])

S.isnumeric ()

S.strip ([chars])

S.isprintable ()

S.swapcase ()

S.isspace ()

S.title ()

S.istitle ()

S.translate (map)

S.isupper ()

S.upper ()

S.join (iterable)

S.zfill (width)

1.5 Python's string manipulation function

in Python There are all kinds of string The action function. In history, the string class has experienced a history of samsara in Python. At the very beginning, Python has a dedicated string modulethat uses string to import first, But then, because of the numerous suggestions from Python users , starting with python2.0, the string method is changed to be called in the form of S.method () , as long as s is a string object that can be used instead of import. At the same time, in order to maintain backward compatibility, A string module is still retained in python, where the method defined is the same as S.method (). All of these methods end up pointing to a function called with S.method () . Note that S.method () can invoke more methods than string in the module , such as IsDigit (), Istitle () and so on can only use S.method () called by the method.

for a String object, the first thought might be to calculate how many characters it has, and it's easy to think of using S.len () , but this is wrong, it should be Len (S) . Because Len () is a built- in function, included in the __builtin__ module. Python does not include Len () in the string type, at first glance it seems a bit incomprehensible, in fact, everything has its logical logic inside . Len () calculates not only the number of characters in a string, but also the number of members of a list , The number of members of a tuple, and so on, so that Len () is counted only in string is inappropriate , so one can use Len () as a general function, with overloads for different types of operations, and with Len () in each A Len () function is included in the type of Operation . Python chooses the first solution. Similar to the STR (ARG) function, it is represented by the string type arg.

1.5.1 character-case transformations in strings

s.lower () # lowercase

S.upper () # Uppercase

s.swapcase () # uppercase and lowercase swaps

s.capitalize () # Capitalize first letter

String.capwords (S)

 # This is the method in the module. It separates S with the split () function, then uses capitalize () to capitalize the initial letter and merge it with join ().

S.title () # only the first letter is capitalized and the remainder is lowercase, this method is not available in the module

1.5.2 the alignment of strings at output

S.ljust (Width,[fillchar])

# Output Width characters, S left-justified, less part with Fillchar padding, the default is a space.

S.rjust (Width,[fillchar]) # Align Right

s.center (width, [Fillchar]) # Middle Alignment

S.zfill (width) # put S Become width long, and in the right alignment, the less part with 0 Topping up

1.5.3 Search and Replace in a string

S.find (substr, [Start, [end]])

 # return S substr appears in the first letter of the label, if S no substr in the then return-1 . Start and end function is equivalent to searching in S[start:end]

S.index (substr, [Start, [end]])

 # with the Find () same, just in S no substr in the , a run-time error is returned

S.rfind (substr, [Start, [end]])

 # return S the last appearance of the substr the first letter of the label, if S no substr in the then return-1 , which means the first occurrence of the substr from the right. the first letter marking

S.rindex (substr, [Start, [end]])

S.count (substr, [Start, [end]]) # Calculate substr in S number of occurrences in

S.replace (Oldstr, Newstr, [Count])

 # put S Oldstar in the to replace with Newstr , Count is the number of replacements. This is a common form of substitution, and there are some functions for replacing special characters

S.strip ([chars])

 # put S chars in front and back all of the characters are removed and can be understood as the S front and rear chars Replace to none

>>> s= ' ABCD '

>>> S.strip (' a ')

' BCD '

S.lstrip ([chars])

S.rstrip ([chars])

S.expandtabs ([tabsize])

Describe:

Python expandtabs () method to put the tab in a string symbol (' \ t ') to a space, the default number of spaces Tabsize is 8 .

Grammar:

Expandtabs () method Syntax:

Str.expandtabs (tabsize=8)

S.split ([Sep, [Maxsplit]])

# with Sep as a delimiter, put S into a list . Maxsplit represents the number of splits. The default delimiter is a blank character

S.rsplit ([Sep, [Maxsplit]])

S.splitlines ([keepends])

 # put S break into a list by line separator , Keepends is a bool values, and row separators are preserved if they are true for each row.

s.join (seq) # put the SEQ the sequence of the representation--the string sequence, with S Link Up

>>> s=[' abcdef ']

>>> s

[' ABCdef ']

>>> s= ' abcdef '

>>> '-'. Join (s)

' A-b-c-d-e-f '

>>> '-'. Join (' abc ')

' A-b-c '

>>> '-'. Join ([' abc ', ' UVW ', ' de ')

' Abc-uvw-de '

>>> ",". Join ({' A ': 1, ' B ': 2, ' C ': 3})

' A,c,b '

>>> ",". Join ([' A ', ' B ', ' C ')

' A,b,c '

>>> ",". Join ((' A ', ' B ', ' C '))

' A,b,c '

Mapping of the 1.5.4 string

This feature consists of two functions:

String.maketrans (from, to)

 # returns a a translation table (map) of characters, where the from the characters in the one by one are converted to , so from and to must be of equal length.

S.translate (Table[,deletechars])

 # using the above function to produce the translation table, put S To translate, and put Deletechars some of the characters are erased. It's important to note that.

>>> Import String # Import String Module

>>> map = String.maketrans (' 123 ', ' abc ') # Create a mapping table that will contain the string ' 1 ', ' 2 ', ' 3 ' Replace with ' a ', ' B ', ' C '

>>> s = ' 54321123789 ' # the string before the conversion

>>> s.translate (map) # map with the created mapping table Convert String

' 54cbaabc789 '

Note: if s to Unicode string, then Deletechars is not supported parameter, you can use to translate a character to none implement the same functionality in the same way. You can also use the functionality of the codecs module to create more powerful translation tables.

The 1.5.5 string also has a pair of encoded and decoded functions

S.encode ([encoding,[errors]])

 # where encoding can have multiple values, such as

gb2312 GBK gb18030 bz2 zlib big5 bzse64 and so on all support. the default value for errors is "strict", which means Unicodeerror. Possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and all through Codecs.register_error the registered value. This section covers the codecs module.

S.decode ([encoding,[errors]])

a test function for a string, which is a type of function not in the module, these functions return all bool values:

S.startwith (Prefix[,start[,end])

 # whether to prefix Start

S.endwith (Suffix[,start[,end])

 # with suffix End

S.isalnum ()

 # are all letters and numbers, and at least one character

S.isalpha () # are all letters, and at least one character

s.isdigit () # are all numbers, and at least one character

s.isspace () # are all whitespace characters, and at least one character

s.islower () #S whether the letters in the letter are all lowercase

s.isupper () #S whether the letters in the letter are all uppercase

s.istitle () #S is the first letter capitalized?

1.5.6 String type conversion function

These functions are only in string The modules are:

String.atoi (S[,base])

#base default is ten , if it is 0, so S it could be 012 . or 0x23 this form of string, if it is so S It's only 0x23 . or 0x12 this form of string

String.atol (S[,base]) # turn it into a long

String.atof (S[,base]) # turn into float

once again, the string object is immutable, meaning that in Python after creating a string, you cannot change a part of the character. Any of the above functions will return a new string after the string has been changed, and the original is not changed. In fact, this is also a flexible approach, you can use S=list (s) This function to change S to a single character as a member of the list, so that can be used s[3]= ' a ' Change the value, and then use s= "". Join (S) to revert to a string.

Example:

>>> list1=[' abc ', ' Def ', ' UVW ']

>>> "". Join (List1)

' ABCDEFUVW '

1.6 Getting module Help

Help (String)

Help (Len)

Help (' Len ')

python_04-string manipulation

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.