Python7: String

Source: Internet
Author: User
Tags printable characters

In Python, the string corresponds to the object str, and the string is an immutable sequence that uses Unicode encoding.

Construct a string

A string can use the following syntax:
1) Single quote: ' Allows embedded ' double ' quotes '
2) Double quotes: "Allows embedded ' single ' quotes"
3) Three quotes: "' Three single quotes", "" "three double quotes" "
A string of three quotes can be extended in multiple lines-all spaces will be included in the string, for example:

>>> ' threesingleqiptes ' ' three\nsingle\nqiptes '
A string that is part of a single expression and that has only spaces between them is implicitly converted to a single string, for example:

>>> "spam" "eggs" ' Spam eggs '
Strings can also be constructed using the Str constructor:
Class str (object= ")
Class str (object=b ', encoding= ' utf-8 ', errors= ' strict ')
STR () returns a String object. If object is not provided, the default is to return an empty string, otherwise, the behavior of STR () depends on whether encoding or errors provides:
1) Encoding and errors are not provided, and STR (object) returns OBJECT.__STR__ (), which is used to represent the string description of the object, which is itself for the string. Returns REPR (object) If the object does not have a __str__ () method;
2) encoding and errors one is provided, the object should be a Bytes-like object (for example: bytes or ByteArray). If object is a bytes (or bytearray), then str (bytes, encoding, errors) is equivalent to Bytes.decode (encoding, errors), otherwise, in the call Bytes.decode ( ) before the Byte object under object will be fetched.
Note Using str () for bytes objects without specifying encoding or errors is equivalent to the descriptive information of the returned object, with 1, such as:

>>> Str (b ' test! ') " B ' test! ' "
Let's look at an example:

Class Strtest ():    def __str__ (self):        return "This is Strtest"    print (str (strtest ()))
Print Result: This is strtest

String method

The string implements the public methods of all the sequences, and adds many additional methods.

Str.capitalize ()

Returns a copy of the string, the first character uppercase, and the other lowercase characters.

Str.casefold ()

Returns a casefolded copy of a string that casefolded string can be used for caseless matching.
Casefolding is similar to lowercase, but further, because it removes all differences in the string. For example, the lowercase letter of German corresponds to "SS", because it is already lowercase, so lower () will not do anything, but Casefold () will convert it to "SS".

Str.center (width[, Fillchar])

Returns a width-length string that, if width is greater than Len (s), is populated with Fillchar (the default space), and S is placed in a central location, such as:

>>> s = ' test ' >>> s.center (' * ') ' ***test*** '

Str.count (sub[, start[, end]])

Returns the number of times a sub appears in Str, with the optional argument start and end used to limit the return.

Str.encode (encoding= "Utf-8", errors= "strict")

Returns a bytes object that uses encoding encoding.

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

If the string ends with suffix, the return true,suffix can be a tuple, and returns True if one of the elements matches, for example:

>>> s = ' test ' *4>>> s.endswith (' test ') true>>> s.endswith (' test1 ', ' test2 ', ' Test ') True

Str.expandtabs (tabsize=8)

Returns a copy of STR, where all tab characters are replaced by one or more spaces, depending on the specified tabsize, default 8.

>>> ' 01\t012\t0123\t01234 ' expandtabs () '      012     0123    01234 ' >>> ' 01\t012\t0123\ T01234 '. Expandtabs (4) '  012 0123    01234 '

Str.find (sub[, start[, end]])

Returns the smallest index the sub was found in Str, or 1 if not found.
Note that find should only be used to query the position of a sub, and if the sub is in a string, in operation:

>>> ' Py ' in ' Python ' True

Str.format (*args, **kwargs)

Performs a formatting operation on a string. The string using this method can use the substitution fields contained in parentheses {}, each substitution field either uses the position number, or uses the variable name to return a copy of the string, and all substitution fields are replaced.

>>> "The sum of 1 + 2 is {0}". Format (1+2) ' The sum of 1 + 2 is 3 '

Str.format_map (mapping)

Added in version 3.2, see the following example:

>>> class Default (dict):d ef __missing__ (Self, key): Return key>>> ' {name} is born in {country} '. Format _map (Default (name= ' Guido ')) ' Guido is born in country '

Str.index (sub[, start[, end]])

Same as find (), except that the ValueError exception is thrown when the substring is not found.

Str.isalnum ()

Returns true if all the characters in the string are alphanumeric, and returns false if one word printable an alphanumeric number. The character c is an alphanumeric representation of one of the following methods that returns True:c.isalpha (), C.isdecimal (), C.isdigit (), or c.isnumeric ().

Str.isalpha ()

Returns true if all characters in the string are letters.

Str.isdecimal ()

Returns true if all characters in the string are decimal digits.

Str.isdigit ()

Returns true if all characters in the string are numbers.

Str.isidentifier ()

Whether the string is a valid identifier.

Str.islower ()

Returns true if all characters in the string are lowercase.

Str.isnumeric ()

Returns true if all characters in the string are numeric characters.

Str.isprintable ()

Returns True if the string is empty, or if the number in the string is printable. Non-printable characters include the Unicode character set labeled "Other" and "Separator".

Str.isspace ()

Returns True if the string is full of spaces.

Str.istitle ()

Returns True if the string is title, which is capitalized in the first letter.

Str.isupper ()

Returns true if the character Embox in the string is uppercase.

Str.join (iterable)

Returns a string of elements in iterable, separated by Str in iterable. Throws an TypeError exception if iterable has an element that is not str.

>>> s = ' asss ' >>> s.join ([' 1 ', ' 2 ', ' 3 ', ' 4 ']) ' 1ASSS2ASSS3ASSS4 '

Str.ljust (width[, Fillchar])

Returns a string that does the width of the appropriate length, padding with Fillchar, and if the string length is greater than or equal to width, the original string is returned.

>>> s = ' 12345678 ' >>> s.ljust (6) ' 12345678 ' >>> s.ljust (+) ' 12345678       ' >>> S.ljust (15, '% ') ' 12345678%%%%%%% '

Str.lower ()

Returns a copy of all characters of the lowercase str.

Str.lstrip ([chars])

Returns a copy of the STR that removes the specified starting character and, if chars is not specified, removes the space by default.

>>> s = '   spaciout   ' >>> s.lstrip () ' Spaciout   ' >>> s.lstrip (' s ') '   spaciout   ' >>> s.lstrip (' s ') ' Paciout   ' >>> s.lstrip (' sp ') ' Aciout   ' >>> s.lstrip (' P ') ' Spaciout   '

Static Str.maketrans (x[, y[, z])

A static method that is used to generate a conversion table for Str.translate ().
If there is only one argument, the argument must be a dictionary, if two arguments, it must be a string of equal length, and if 3 arguments, the third argument must be a string, and the character of the string will be matched to none.

>>> Str.maketrans ({' A ': ' A ', ' B ': ' B '}) {: ' A ', 98: ' B '}>>> Str.maketrans (' abc ', ' abc ') {97:65, 98:66, 99:67}>>> Str.maketrans (' abc ', ' abc ', ' Def ') {97:65, 98:66, 99:67, 100:none, 101:none, 102:none}
See the Translate method for more detailed use.

Str.partition (Sep)

Detach the string from the first occurrence of the Sep section, and get a tuple of 3 elements: the part before Sep, Sep, and after Sep. If Sep is not found, it still returns a tuple of 3 elements: str, an empty string, and an empty string.

>>> s = ' 123456789 ' >>> s.partition (' 123 ') (' 6789 ') >>> s.partition (' 666 ') (' 123456789 ', ', ')

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

Returns a new string in which all old are replaced by new, and count is used to specify that only the first count is replaced.

Str.rfind (sub[, start[, end]])

Returns the index number of the last occurrence of the sub in Str, returning 1 to indicate that it was not found.

Str.rindex (sub[, start[, end]])

Same as RFind, but throws ValueError if the sub is not found.

Str.rjust (width[, Fillchar])

See Ljust,rjust means right fit.

Str.rpartition (Sep)

See Partition,rpartition to find Sep from right.

Str.rsplit (Sep=none, Maxsplit=-1)

Use Sep to separate str,maxsplit to indicate the maximum number of divisions, Sep does not specify or none, then use a space to separate str.

>>> s = ' 12345 ' * 8>>> s.rsplit (' a ') [' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ']>> ' ;> s.rsplit (' 45 ', 6) [' 1234512345123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ' 123 ', ']

Str.rstrip ([chars])

Returns the copy of STR, the character at the end is removed, the space is removed by default, and chars represents the removed character set.

>>> '   spacious   '. Rstrip () '   spacious ' >>> ' Mississippi '. Rstrip (' Ipz ') ' Mississ '

Str.split (Sep=none, Maxsplit=-1)

Look at Rsplit, which returns a list using Sep, separated by a space if Sep is unspecified. Maxsplit indicates the maximum number of separators.

Str.splitlines ([keepends])

Use that line terminator to separate STR and return a list of rows. Keepends defaults to False, which indicates that the row delimiter is not included in the results list.

>>> ' ab C\n\nde fg\rkl\r\n '. Splitlines () [' Ab C ', ', ' de fg ', ' KL ']>>> ' ab C\n\nde fg\rkl\r\n '. Splitlin ES (keepends=true) [' Ab c\n ', ' \ n ', ' de fg\r ', ' kl\r\n ']
Note the difference from split:

1) for an empty string, Splitlines returns an empty list, split returns a list that contains an empty string.

>>> "One line\n". Splitlines () [' one line ']>>> ' lines\n '. Split (' \ n ') [' Both lines ', ']
2) for a string ending with a line terminator, Splitlines returns a list of the individual elements, and split returns a list of two elements.

>>> "". Splitlines () []>>> ". Split (' \ n ') [']

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

If the string starts with prefix, the return true;prefix can be a tuple.

>>> s = ' hello!world. ' >>> s.startswith (' hello ') true>>> s.startswith ((' Hello ', ' hello ')) True

Str.strip ([chars])

Returns a copy of STR and removes the kinsoku characters (the default blank).

>>> '   spacious   '. Strip () ' spacious ' >>> ' www.example.com '. Strip (' Cmowz. ') ' Example

Str.swapcase ()

Return the copy of STR and convert case, note s.swapcase (). Swapcase () = = S.

>>> s = ' aBcDe ' >>> s.swapcase () ' ABcDe '

Str.title ()

Returns a copy of STR with the first letter of each word capitalized and the remaining letters lowercase.

>>> ' Hello World '-title () ' Hello World ' >>> ' they ' re Bill's friends from the UK ". Title ()" They ' re bill ' s F Riends from the Uk "

Str.translate (map)

corresponding to see Maketrans. Returns a copy of STR, where all characters are mapped using map.

>>> ' abcdefg-1234567 ' Translate (Str.maketrans (' abc ', ' abc ') ' ABCdefg-1234567 ' >>> ' abcdefg-1234567 '. Translate (Str.maketrans (' abc ', ' abc ', ' 456 ')) ' ABCdefg-1237 '

Str.upper ()

Returns a copy of STR, where the characters are converted to uppercase. Note If Str contains characters that are not uppercase (uncased), Str.upper (). Isupper () will get false.

Str.zfill (width)

Returns a copy of str, length width, left with 0 padding, and if Str starts with ' + '/'-', the padding starts after ' + '/'-'.

>>> "Zfill" (5) ' 00042 ' >>> ' -42 '. Zfill (5) '-0042 '

Formatted printing of strings

The string supports the% operation, which is used to format the string, similar to sprintf () in the C language.
When formatting requires only one argument, the value can be a single string, otherwise the value must be a tuple or a mapped object with an equal parameter length.
The basic conversion specifier includes the following sections:
1)% character: mark conversion specifier position;
2) the conversion flag (optional):-Indicates left alignment, + denotes a sign before the value is converted, "" (white space character) represents an integer before the space is reserved, and 0 indicates that the conversion value is filled with 0 if the number of bits is not enough;
3) Minimum character width (optional): The minimum character width after conversion;
4) point (.) followed by the precision value (optional): If it is a real number, it indicates the digits after the decimal point, or the maximum field width if it is a string;
5) Conversion Type:
D,i: Signed decimal number
0: Octal with no symbols
U: Non-signed decimal
x: Unsigned hexadecimal (large, lowercase)
E: Floating-point numbers represented by scientific notation (both large and lowercase)
F: Decimal Floating-point number (both large and lowercase)
G: If the exponent is greater than 4 or less than the progress value is the same as E, otherwise with f (large, lowercase can be)
C: Single-character (accepts integers or single character strings)
R: String (convert any Python object using repr)
S: string (convert any Python object using str)
Look at the following example.

Direct conversion

>>> "I ' m%s. I ' m%d year old "% (' Tomato ',") "I ' M Tomato. I ' m old ">>> from math import pi>>> ' pi:%f ... '% pi ' pi:3.141593 ... '

Specifying width and precision

>>> ' pi:%10f '% pi ' pi:   3.141593 ' >>> ' pi:%10.2f '% pi ' pi:       3.14 ' >>> '%.5s '% ' this is a Test ' this '
You can use * as the character width or precision, when the value is read from the tuple parameter:

>>> '%.*s '% (8, ' This was a test ') ' This is '

Symbols, alignments, and 0 fills

Use '-' to indicate left alignment:

>>> '%10.2f '% pi '      3.14 ' >>> '%-10.2f '% pi ' 3.14      '
Using 0 means that the number will be populated with 0:

>>> '%010.2f '% pi ' 0000003.14 '
"" means a space preceded by an integer with a negative number that is used to align negative numbers:

>>> print (('% 5d ') + ' \ n ' + ('% 5d '% -10))  -10
+ denotes a symbol regardless of whether it is an integer or a negative number:

>>> print ('%+5d '%) + ' \ n ' + ('%+5d '% -10))  +10  -10


Python7: String

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.