Python7: String, python7 string

Source: Internet
Author: User
Tags iterable

Python7: String, python7 string

In Python, the string corresponds to the str object, and the string is an unchangeable sequence encoded using Unicode.

Construct a string

Strings can use the following syntax:
1) single quotes: 'allows embedded "double" quotes'
2) double quotation marks: "allows embedded 'single 'quotes"
3) Three quotation marks: '''three single quotes ''', "" Three double quotes """
A string with three quotation marks can be expanded in multiple rows-all spaces will be included in the string, for example:

>>> '''threesingleqiptes''''three\nsingle\nqiptes'
Strings that are part of a single expression and have only spaces between them are implicitly converted to a single string. For example:

>>> "spam " "eggs"'spam eggs'
You can also use the str constructor to construct a string:
Class str (object = '')
Class str (object = B '', encoding = 'utf-8', errors = 'strict ')
Str () returns a String object. If the object is not provided, an empty string is returned by default. Otherwise, the str () action depends on whether encoding or errors provides:
1) encoding and errors are not provided. str (object) returns object. _ str _ (), which indicates the string description of the object. For a string, it is itself. If the object does not have the _ str _ () method, the repr (object) is returned );
2) One of encoding and errors is provided. The object should be a bytes-like object (for example, bytes or bytearray ). If the object is a bytes (or bytearray), str (bytes, encoding, errors) is equivalent to bytes. decode (encoding, errors), otherwise, in the call bytes. before decode (), The Byte object under the object will be obtained.
Note that if encoding or errors is not specified, using str () for a bytes object is equivalent to the description of the returned object, which is the same as 1, for example:

>>> str(b'test!')"b'test!'"
The following is an example:

class StrTest():    def __str__(self):        return "this is StrTest"    print(str(StrTest()))
The result is: this is StrTest.

String Method

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

Str. capitalize ()

Returns a copy of the string. The first character is in upper case, and the other characters are in lower case.

Str. casefold ()

Returns the casefolded copy of a string. The casefolded string can be used for caseless matching.
Casefolding is similar to lowercase, but goes further because it removes all the differences in strings. For example, lowercase letters in German correspond to "ss". Since it is already in lowercase, lower () will not do anything, but casefold () will convert it to "ss ".

Str. center (width [, fillchar])

Returns a string with the length of width. If the width is greater than len (s), fill it with fillchar (default space) and place s in the center, for example:

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

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

Returns the number of times that sub appears in str. The optional start and end parameters are used to limit the return.

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

Returns a bytes object encoded with encoding.

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

If the string ends with suffix, true is returned. suffix can be a tuples. If one of the elements matches, true is returned. For example:

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

Str. expandtabs (tabsize = 8)

Returns a copy of str. All the tab characters are replaced by one or more spaces. The default value is 8, depending on the specified tabsize.

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

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

Returns the minimum index found by sub in str. If no index is found,-1 is returned.
Note that find should only be used to query the sub location. If you want to determine whether the sub is in the string, use the in operation:

>>> 'Py' in 'Python'True

Str. format (* args, ** kwargs)

Format the string. The string using this method can use the replacement domain contained in brackets {}. Each replacement domain or position number, or variable name, returns a copy of the string, and all replacement domains are replaced.

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

Str. format_map (mapping)

Add it in version 3.2. See the following example:

>>> class Default(dict):def __missing__(self, key):return key>>> '{name} was born in {country}'.format_map(Default(name='Guido'))'Guido was born in country'

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

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

Str. isalnum ()

If all characters in a string are letters and numbers, true is returned. If one character is not a letter or number, false is returned. The character c is a letter or number, indicating that one of the following methods 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 in lower case.

Str. isnumeric ()

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

Str. isprintable ()

If the string is null or the numbers in the string are printable, true is returned. Unprintable characters include those marked as "Other" and "Separator" in the unicode Character Set.

Str. isspace ()

Returns true if all strings contain spaces.

Str. istitle ()

If the string is title, true is returned, that is, the first letter is capitalized.

Str. isupper ()

Returns true if all characters in the string are uppercase.

Str. join (iterable)

Returns the Union string of elements in iterable. Elements in iterable are separated by str. If the iterable has a non-str element, a TypeError exception is thrown.

>>> s = 'Asss'>>> s.join(['1','2','3','4'])'1Asss2Asss3Asss4'

Str. ljust (width [, fillchar])

Returns a string adapted to the width. The blank space is filled with fillchar. If the length of the string is greater than or equal to width, the original string is returned.

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

Str. lower ()

Returns a copy of str with all characters in lower case.

Str. lstrip ([chars])

Returns the copy of str with the specified start character. If chars is not specified, spaces are removed 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])

Static method, used to generate a conversion table for str. translate.
If there is only one parameter, the parameter must be a dictionary. If there are two parameters, the parameter must be a string of equal length. If there are three parameters, the third parameter must be a string, and the character of this string will be matched to None.

>>> str.maketrans({'a':'A','b':'B'}){97: '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}
For more details, see the translate method.

Str. partition (sep)

Separate the string from the first sep part to obtain the tuples of three elements: the parts before sep, the parts after sep, and sep. If sep is not found, a triple of three elements is returned: str, null string, and null string.

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

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

Returns a new string, where all old values are replaced by new, and count is used to specify to replace only the previous count values.

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

Returns the index number of sub in str.-1 indicates that no index is found.

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

Same as rfind, but if sub is not found, ValueError is thrown.

Str. Fill ust (width [, fillchar])

When we look at ljust, must ust indicates right adaptation.

Str. rpartition (sep)

Look at partition. rpartition indicates searching for sep from the right.

Str. rsplit (sep = None, maxsplit =-1)

Use sep to separate str. maxsplit indicates the maximum number of splits. If sep is not specified or is none, use a space to separate str.

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

Str. rstrip ([chars])

Returns a copy of str. The character at the end is removed. spaces are removed by default. chars indicates the removed character set.

>>> '   spacious   '.rstrip()'   spacious'>>> 'mississippi'.rstrip('ipz')'mississ'

Str. split (sep = None, maxsplit =-1)

When you look at rsplit, a list separated by sep is returned. If sep is not specified, spaces are used to separate the list. Maxsplit indicates the maximum number of times of separation.

Str. splitlines ([keepends])

Use the line terminator to separate str and return a list of rows. The default value of keepends is false, indicating that the row separator is not included in the result list.

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()['ab c', '', 'de fg', 'kl']>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Note:

1) For empty strings, splitlines returns an empty list, and split returns a list containing an empty string.

>>> "One line\n".splitlines()['One line']>>> 'Two lines\n'.split('\n')['Two lines', '']
2) For the string ending with the row Terminator, splitlines returns the list of individual elements, and split returns the list of two elements.

>>> "".splitlines()[]>>> ''.split('\n')['']

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

If the string starts with prefix, true is returned; 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 first and last characters (blank by default ).

>>> '   spacious   '.strip()'spacious'>>> 'www.example.com'.strip('cmowz.')'example'

Str. swapcase ()

Returns a copy of str and converts it to uppercase or lowercase. Note that s. swapcase (). swapcase () = s.

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

Str. title ()

Returns a copy of str. the first letter of each word is uppercase, And the other letters are lowercase.

>>> 'Hello woRld'.title()'Hello World'>>> "they're bill's friends from the UK".title()"They'Re Bill'S Friends From The Uk"

Str. translate (map)

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 all characters are converted to uppercase. Note that if str contains characters in the case-free format (uncased), str. upper (). isupper () returns false.

Str. zfill (width)

Returns a copy of a str with the length of width. The left side is filled with 0. If str starts with '+'/'-', it starts with '+.

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

String formatting

The string supports the % operation, which is used to format the string, similar to sprintf () in C language ().
If only one parameter is required for formatting, the value can be a single string. Otherwise, the value must be a tuple or ing object of the same length as the parameter.
The basic conversion specifiers include the following:
1) % characters: Mark the conversion operator position;
2) Conversion sign (optional):-indicates the left alignment; + indicates adding a plus or minus sign before the conversion value; "" (blank character) indicates retaining spaces before the integer; 0 indicates that the conversion value is filled with 0 if the number of digits is not enough;
3) minimum character width (optional): minimum character width after conversion;
4) Point (.) followed by precision value (optional): If it is a real number, it indicates the number of digits after the decimal point; if it is a string, it indicates the maximum field width;
5) Conversion Type:
D, I: signed decimal number
0: Unsigned octal chart
U: Unsigned decimal
X: Non-Signed hexadecimal format (both big and lowercase)
E: floating point numbers represented by scientific notation (both big and lowercase)
F: decimal floating point number (both big and lowercase)
G: If the index is greater than-4 or smaller than the progress value, it is the same as e; otherwise, it is the same as f (both big and lowercase)
C: single character (accept integer or single character string)
R: string (use repr to convert any Python object)
S: string (use str to convert any Python object)
Let's look at the example below.

Direct Conversion

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

Specify 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. In this case, the value is read from the tuples:

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

Symbol, alignment, and 0 Filling

Use '-' To Indicate left alignment:

>>> '%10.2f' % pi'      3.14'>>> '%-10.2f' % pi'3.14      '
0 indicates that the number will be filled with 0:

>>> '%010.2f' % pi'0000003.14'
"" Indicates that a space is added before the integer, and the negative number remains unchanged, which is used for positive and negative correction:

>>> print(('% 5d' % 10) + '\n' + ('% 5d' % -10))   10  -10
+ Indicates that both integer and negative numbers indicate the exit symbol:

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


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.