1)They can be enclosed in single quotes ('...'
) or double quotes ("..."
) with the same result. can be used to escape quotes
2)If you don’t want characters prefaced by to be interpreted as special characters, you can use raw strings by adding an
r
before the first quote
3)String literals can span multiple lines. One way is using triple-quotes: """..."""
or '''...'''
. End of lines are automatically included in the string, but it’s possible to prevent this by adding a at the end of the line. The following example
4)Strings can be concatenated (glued together) with the +
operator, and repeated with *
# equals to 'xxxxx'
'x' * 5
5)Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.This only works with two literals though, not with variables or expressions.
6)Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one.
7)Indices may also be negative numbers, to start counting from the right.Note that since -0 is the same as 0, negative indices start from -1.
8)In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring. Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s. Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
9)Attempting to use an index that is too large will result in an error. However, out of range slice indexes are handled gracefully when used for slicing.
10)Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error.
11)The built-in function len()
returns the length of a string
12)比较常用的方法是:find, 它可以返回子串首次匹配的位置:
'hello'.find('l') # return 2
上面所述都是string的基本特点,另外string本身也是一个class,所以它还有很多其它的方法,而且很多,API地址如下:
https://docs.python.org/3/library/stdtypes.html#string-methods