Python Getting Started: strings and python getting started

Source: Internet
Author: User
Tags print format string methods

Python Getting Started: strings and python getting started

All standard sequence operations apply to strings, but strings are immutable.

String constant:

Single quotes: 'spa "M'

Double quotation marks: "spa m"

Three quotation marks: '''... spam... ''', ""... spam ..."""

Escape Character: "s \ tp \ na \ om"

Raw string: r "C: \ new \ test. spm"

Unicode string: u'eggs \ u0020spam

Single double quotation marks are the same
Single double quotes can be exchanged, and character constant expressions can be expressed using two single quotes or two double quotes-two forms are also valid to return objects of the same type:

Copy codeThe Code is as follows:
>>> 'Zxcvbn ', "zxcvbn"
('Zxcvbn ', 'zxcvbn ')
>>># Escape characters are not applicable, so you can enclose the quotation marks of other types in a string.
>>> 'Ight "s '," knight's"
('Ight "s'," knight's ")

It can automatically merge adjacent string constants in any expression, even though it can be implemented using the + operator:

Copy codeThe Code is as follows:
>>> Title = "sdfsd" 'dfg' "FGD"
>>> Title
'Sdfsddfgfd'

Character % is used for string formatting:

Put a string on the left side of %, and put the value to be formatted on the right side. You can use one value or the tuples or dictionaries of multiple values.

Copy codeThe Code is as follows:
>>> Format = "Hello. % s. % s enough for ya? "
>>> Values = ('World', 'hot ')
>>> Print format % values
Hello. world. Hot enough for ya?

If the tuples to be converted exist as part of the conversion expression, you must enclose them in parentheses to avoid errors.

Long String, original string
1. Long String

If you want to write a very long string and need to span multiple rows, you can use three quotation marks to replace the common quotation marks.

Copy codeThe Code is as follows:
>>> Print ''' this is
A
Very long
String '''
This is
A
Very long
String

If the last character in a line is a backslash, The linefeed itself will be "escaped", that is, ignored.

Copy codeThe Code is as follows:
>>> Print "hello .\
World! "
Hello. world!
>>># This usage also applies to expressions and statements
>>> 1 + 2 + \
4 + 5
12
>>> Print \
'Hello. world'
Hello. world

2. original string

The original string starts with r. You can add any character to the original string. The output string contains the backslash used for escape. However, you cannot enter a backslash at the end of the string:

Copy codeThe Code is as follows:
>>> Print \
'Hello. world'
Hello. world
>>> Print r'let \'s go! '
Let \'s go!
>>> Print r'this is illegal \'
SyntaxError: EOL while scanning string literal

Index and sharding

The character of a string is extracted by indexing and a character string at a specific position is obtained.

The Python offset starts from 0 and is 1 smaller than the length of the string. It also supports methods similar to using negative offset in the string to obtain elements from the sequence, negative offset refers to reverse counting from the end

When a sequence object such as an offset index string separated by a colon is used, all elements from the lower boundary until but not including the upper boundary are obtained.

The index (s [I]) gets the element of a specific offset:

The offset of the first element is 0.

Negative offset index means counting from the last or right reverse

S [0] Get the first element

S [-2] obtains the penultimate element.

Parts (s [I: j]) are extracted as a sequence:

The upper boundary is not included.

By default, the shard boundary is 0 and the sequence length. If not

S [] gets the element with the offset of 1 until it does not include the element with the offset of 3.

S [1:] obtains the element from the offset of 1 till the end.

S [: 3] obtains the element from the offset of 0, but does not include the element with the offset of 3.

S [:-1] obtains the element from the offset of 0 until it does not include the last element.

S [:] obtains the element from the offset 0 to the end.

Copy codeThe Code is as follows:
>>> S = 'spam'
>>> S [0], s [-2]
('S ', 'A ')
>>> S [1: 3], s [1:], s [:-1]
('Pa', 'pam ', 'pa ')
>>> S [0], s [-2]
('S ', 'A ')

Extended parts: the third limit value

The fragment expression adds an optional third index that is used as a stepping X [I: J: K] representation: the elements in the index X object, from offset to I until offset is J-1, index every K element

Copy codeThe Code is as follows:
>>> S = 'abcdefhijklmnop'
>>> S []
'Bdfhj'
>>> S [: 2]
'Acegikm'
>>> S = 'hello'
>>> S [:-1]
'Olleh'
>>> S [4: 1:-1]
'Oll'

String Conversion Tool

Copy codeThe Code is as follows:
>>> '42' + 1
Traceback (most recent call last ):
File "<pyshell #40>", line 1, in <module>
'42' + 1
TypeError: cannot concatenate 'str' and 'int' objects
>>> Int ('42'), str (42)
(42, '42 ')
>>> Repr (42), '42'
('42', '42 ')
>>> S = '42'
>>> I = 1
>>> S + I
Traceback (most recent call last ):
File "<pyshell #45>", line 1, in <module>
S + I
TypeError: cannot concatenate 'str' and 'int' objects
>>> Int (s) + I
43
>>> S + str (I)
'123'
>>># Similarly, you can convert a floating point to a string or a string to a floating point.
>>> Str (3.1415), float ("1.3 ")
('3. 100', 1415)
>>> Text = '1. 23E-10'
>>> Float (text)
1.23e-10

String Code Conversion

A single character can also be converted to its corresponding ASCII code by passing it to the built-in ord function, while the chr function performs the opposite operation:

Copy codeThe Code is as follows:
>>> Ord ('s ')
115
>>> Chr (1, 115)
'S'

String Method

Strings are much richer than list methods, because strings are inherited from the string module. This article only introduces some particularly useful string methods.

1. find

The find method can be used to search for a substring in a long string. It returns the leftmost index of the substring location. If no substring is found,-1 is returned.

Copy codeThe Code is as follows:
>>> 'With a moo-moo here, and a moo-moo there'. find ('moo ')
7
>>> Title = "Monty Python's Flying Cirus"
>>> Title. find ('monty ')
0
>>> Title. find ('python ')
6
>>> Title. find ('zirquss ')
-1

This method can accept the optional start and end parameters:

Copy codeThe Code is as follows:
>>> Subject = '$ Get rich now !!! $'
>>> Subject. find ('$ ')
0
>>> Subject. find ('$', 1)
20
>>> Subject. find ('!!! ')
16
>>> Subject. find ('!!! ', 0, 16)
-1

2. join

The join method is a very important string method. It is the inverse method of the split method, used to add elements to the queue:

Copy codeThe Code is as follows:
>>> Seq = [1, 2, 3, 4, 5]
>>> Sep = '+'
>>> Sep. join (seq)

Traceback (most recent call last ):
File "<pyshell #15>", line 1, in <module>
Sep. join (seq)
TypeError: sequence item 0: expected string, int found
>>> Seq = ['1', '2', '3', '4', '5']
>>> Sep. join (seq)
'1 + 2 + 3 + 4 + 5'
>>> Dirs = '', 'usr', 'bin', 'env'

>>> '/'. Join (dirs)
'/Usr/bin/env'
>>> Print 'C: '+' \ '. join (dirs)
C: \ usr \ bin \ env

3. lower

The lower method returns the lower-case string.

Copy codeThe Code is as follows:
>>> 'Hdwud hdjhs lkjds '. lower ()
'Hdwud hdjhs lkjds'

4. replace

The replace method returns the string after all matching items of a string are replaced.

Copy codeThe Code is as follows:
>>> 'This is a test'. replace ('is ', 'eez ')
'Theez eez a Test'

5. split

It is the inverse method of join, used to split strings into Sequences

Copy codeThe Code is as follows:
>>> '1 + 2 + 3 + 4 + 5'. split ('+ ')
['1', '2', '3', '4', '5']
>>> 'C: \ usr \ bin \ env '. split ('/')
['C: \ usr \ x08in \ env']
>>> 'Using the default'. split ()
['Using', ''the, 'default']

NOTE: If no separator is provided, the program uses all spaces as separators.

6. strip

The strip method returns a string that removes spaces on both sides (excluding internal spaces:

Copy codeThe Code is as follows:
>>> 'Internal whitespace is kept '. strip ()
'Internal whitespace is kept'

You can also specify the characters to be removed and column them as parameters:

Copy codeThe Code is as follows:
>>> '*** SPAM ** for * everyone !!! * ** '. Strip ('*! ')
'Spam * for * everone'

Note: Only the characters on both sides are removed.

7. translate

The translate method is the same as the replace method. Some parts of the string can be replaced. However, unlike the former method, the translate method only processes a single character.


Strings in python

For example
Ss = "123456"
Ss. replace ("12", 'A') returns the string "aa3456"
However, the value of ss is still "123456" and does not change.

In contrast
Lst = [1, 2, 4]
Lst. pop (0) returns 1, and the lst also becomes [2, 3, 4]

Immutable means that the method used to call an object cannot change the object itself.

String operation python String Conversion to list

#! /Usr/bin/python
# Encoding: UTF-8

Str = "['mac = $ AUTOGEN_MAC, bridge = xenbr1, model = pcnet', 'mac = 00: 16: 3e: 4b: a2: 30, bridge = xenbr0, model = ']"
Lst = [','. join ([('mac = $ autogen_mac' if item [: 4] = 'mac = 'else item)
For item in m. split (',')])
For m in eval (str)]
Print repr (lst)

#~ > Python-u "test. py"
#~ ['Mac = $ AUTOGEN_MAC, bridge = xenbr1, model = pcnet', 'mac = $ AUTOGEN_MAC, bridge = xenbr0, model = ']
#~ > Exit code: 0 Time: 0.074

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.