Python Introductory article string _python

Source: Internet
Author: User
Tags ord print format string methods

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

String constants:

Single quotation mark: ' Spa ' m '

Double quotes: "Spa ' m"

Three quotes: "... spam", "" "" ... spam ... "" ""

Escape character: "S\tp\na\om"

Raw string: R "C:\NEW\TEST.SPM"

Unicode string: U ' eggs\u0020spam

Single double quotes are the same
Single double quotes can be exchanged, and constants expressions can be represented by two single quotes or two double quotes-two forms also effectively return objects of the same type:

Copy Code code as follows:

>>> ' zxcvbn ', "zxcvbn"
(' zxcvbn ', ' zxcvbn ')
Quotes for >>> #不适用转义字符就可以实现在一个字符串中包含其余种类
>>> ' Knight ' "s", "Knight ' s"
(' Knight ', "s '," Knight ' s ")

You can automatically merge adjacent string constants in any expression, although you can also use the + operator:

Copy Code code as follows:

>>> title= "SDFSD" ' DFG ' "FGFD"
>>> Title
' SDFSDDFGFGFD '

The format of the string is implemented using the character%:

Place a string on the left side of%, place the value you want to format on the right, you can use a value, or you can use a tuple or a dictionary of multiple values

Copy Code code as follows:

>>> format= "Hello. %s.%s enough for ya?
>>> values= (' World ', ' hot ')
>>> Print Format% values
Hello. World. Hot enough for ya?

If you need to convert a tuple that exists as part of a transformation expression, you must enclose it in parentheses to avoid errors

Long string, original string
1, long string

If you need to write a very long string and you need to span multiple lines, you can use three quotes instead of plain quotes

Copy Code code as follows:

>>> print ' ' Is
A
Very long
String ' '
This is
A
Very long
String

If the last character in a line is a backslash, the line break itself is "escaped", which is ignored

Copy Code code as follows:

>>> print "hello.\
world! "
hello.world!
>>> #这个用法也适用表达式和语句
>>> 1+2+\
4+5
12
>>> print \
' Hello.world '
Hello.world

2. Original string

The original string starts with R, can put any character in the original string, and the last output string contains the backslash used to escape, but cannot enter a backslash at the end of the string:

Copy Code code as follows:

>>> print \
' Hello.world '
Hello.world
>>> print R ' let\ ' go! '
Let\ ' s go!
>>> Print R ' This is Illegal\ '
Syntaxerror:eol while scanning string literal

Indexing and partitioning

The character of the string is extracted by the index and will get a string of characters in a particular position.

The python offset starts at 0 and is smaller than 1 of the length of the string, and also supports methods such as using a negative offset in the string to get the element from the sequence, which is considered to be the inverse count from the end

When you use a sequence object such as an offset index string that is separated by a colon, all elements that are from the bottom boundary until they are not included on the top boundary are obtained

Index (S[i]) Gets the element of a specific offset:

The first element has an offset of 0

A negative offset index means that the count is reversed from the last or right

S[0] Gets the first element

S[-2] Gets the penultimate element

The fragment (S[i:j]) extracts the corresponding part as a sequence:

The upper boundary is not included

The piecewise boundary defaults to 0 and the length of the sequence, if not given

S[1:3] Gets an element that is offset to 1, but does not include an element with an offset of 3

S[1:] Gets the element from the offset of 1 to the end

S[:3] Gets an element that is offset from 0 until it does not include an offset of 3

S[:-1] Gets the element from the offset of 0 until the last element is not included

S[:] Gets the element from offset 0 to the end

Copy Code code as follows:

>>> s= ' spam '
>>> S[0],s[-2]
(' s ', ' a ')
>>> S[1:3],s[1:],s[:-1]
(' Pa ', ' Pam ', ' Spa ')
>>> S[0],s[-2]
(' s ', ' a ')

Extended fragmentation: Third limit value

A piecewise expression adds an optional third index, used as a stepping x[i:j:k] representation: An element in an index x object, from offset I until offset to J-1, once per K element

Copy Code code as follows:

>>> s= ' Abcdefghijklmnop '
>>> S[1:10:2]
' Bdfhj '
>>> S[::2]
' Acegikmo '
>>> s= ' Hello '
>>> S[::-1]
' Olleh '
>>> S[4:1:-1]
' Oll '

String Conversion Tool

Copy Code code 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 (' a '), 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)
' 421 '
>>> #类似也可以把浮点数转换成字符串或把字符串转换成浮点数
>>> Str (3.1415), float ("1.3")
(' 3.1415 ', 1.3)
>>> 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, and the CHR function performs the opposite action:

Copy Code code as follows:

>>> Ord (' s ')
115
>>> chr (115)
' s '

String method

The string is much richer than the list method, because the string "inherits" from the string module in many ways, and this article only introduces some of the most useful string methods

1, find

The Find method can look up a substring in a longer string that returns the leftmost index of the substring's location and returns 1 if it is not found

Copy Code code 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 optional start and end point parameters:

Copy Code code 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, which is the inverse method of the split method, which is used to add elements to the queue:

Copy Code code 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

Lower method returns the lowercase master of a string

Copy Code code as follows:

>>> ' Hdwud hdjhs lkjds '. Lower ()
' Hdwud hdjhs lkjds '

4, replace

The Replace method returns a string when all occurrences of a string are replaced

Copy Code code as follows:

>>> ' is a test '. Replace (' is ', ' EEZ ')
' Theez eez a test '

5, split

It is the inverse method of join, which is used to divide the string into sequences

Copy Code code 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 you do not provide any delimiters, the program will take all the blanks as delimiters

6, Strip

The Strip method returns a string that removes both sides (not including internal) spaces:

Copy Code code as follows:

>>> ' internal whitespace is kept '. Strip ()
' Internal whitespace is kept '

You can also specify the characters you want to remove and list them as parameters:

Copy Code code as follows:

>>> ' * * * SPAM * for * everyone!!! '. Strip (' *! ')
' SPAM * for * everyone '

Note: Only the characters on both sides will be stripped

7, translate

The Translate method, like the Replace method, can replace parts of a string, but unlike the former, the translate method handles only a single character

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.