1. 字符串的表示
Python中,字符串可以用双引号 "..." 或者单引号 '...' 括起来表示。当字符串中包含单引号或者双引号时,就可以用另一种引号来包含字符串
"qwer"
Out[1]: 'qwer'
'qwer'
Out[2]: 'qwer'
"qwer'qwre"
Out[3]: "qwer'qwre"
'qwer"qwer'
Out[4]: 'qwer"qwer'
1.1 转义字符:
Python中的转义字符是 '\'. 它用来表示一些特殊的字符,或者用来表示字符串中出现的单双引号
当使用print()对字符串进行输出时,这些特殊字符才会显示。
"hello\tasdf"
Out[7]: 'hello\tasdf'
"hello\'tasdf"
Out[8]: "hello'tasdf"
"hello\"tasdf"
Out[9]: 'hello"tasdf'
"hello\ntasdf"
Out[10]: 'hello\ntasdf'
print("hello\tasdf")
hello asdf
print("hello\'tasdf")
hello'tasdf
print("hello\"tasdf")
hello"tasdf
print("hello\ntasdf")
hello
tasdf
如果在输入字符串时不希望Python中的 \ 承担转义字符的功能,则需要使用raw input,即 r'...'
print(r"hello\tasdf")
hello\tasdf
print(r"hello\'tasdf")
hello\'tasdf
print(r"hello\"tasdf")
hello\"tasdf
print(r"hello\ntasdf")
hello\ntasdf
1.2 字符串跨行
可以使用三个单引号或者三个双引号来跨行定义字符串,在行与行之间会添加换行符
print("""asdfsadfas
asdvdsvsdf
erasdfasdf""")
asdfsadfas
asdvdsvsdf
erasdfasdf
print('''hello
moto''')
hello
moto
s = '''hello
hi'''
s
Out[23]: 'hello\nhi'
2. 字符串连接
2.1 + 号转义
2.2 不添加任何符号,这种做法只适用于字符串本身,不适用与变量和表达式
"123" + "qwe"
Out[24]: '123qwe'
"123" "qwe"
Out[25]: '123qwe'
3. 字符串操作
在Python中,字符串可以被索引和切片
3.1 索引
Python字符串索引从0,开始,如果超出索引范围会报IndexError异常
word = "Python"
word[0]
Out[31]: 'P'
word[8]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-32-40f1e8b7180a> in <module>()
----> 1 word[8]
IndexError: string index out of range
3.2 切片
和直接索引不同的是,在切片时,允许索引超出范围,超出的部分为空字符串
word = "Python"
word[0:3]
Out[41]: 'Pyt'
word[-3:-1]
Out[42]: 'ho'
word[1:20]
Out[43]: 'ython'
3.3 修改字符串
不能通过索引对字符串进行修改。因为在Python3中,字符串是不可变的。如果进行修改则会引发TypeError异常,因为string类型不支持这种操作。
word = "Python"
word[0] = "R"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-45-69b316a88f68> in <module>()
----> 1 word[0] = "R"
TypeError: 'str' object does
word = "Python"
"R" + word[1:6]
Out[50]: 'Rython'
not support item assignment
3.4 创建新字符串
修改字符串的想法的一种替代思路是利用索引和切片创建一个新的字符串
3.5 len()可获得字符串长度
word = "Python"
len(word)
Out[52]: 6
其它关于字符串的内容见下面的文档:
See also
-
Text Sequence Type — str
- Strings are examples of sequence types, and support the common operations supported by such types. String Methods
- Strings support a large number of methods for basic transformations and searching. Format String Syntax
-
Information about string formatting with
str.format()
.
printf-style String Formatting
-
The old formatting operations invoked when strings are the left operand of the
%
operator are described in more detail here.