字符串

Reads: 852 Edit

字符串是由数字、字母、下划线等组成的一串字符!如果用字符串来定义“12”,那么其是无法进行数值运算的。

1 定义字符串

>>> strA='Python2'
>>> strA
'Python2'
>>> type(strA)
<class 'str'>
>>> strB="Python3"
>>> strB
'Python3'
>>> type(strB)
<class 'str'>

说明:可以通过单引号和双引号来定义字符串

2 转义符

>>> strC=""Python3""
SyntaxError: invalid syntax
strD="\"Python3\""
strD
'"Python3"'

说明:如果定义的变量中也包含引号,则需要使用转义符""。

3 字符串操作

3.1 通过索引获取字符串中字符

>>> str='Python'
>>> str[0]
'P'
>>> str[-1]
'n'
>>> str[2]
't'
>>> str[1:3]
'yt'
>>> str[2:]
'thon'

说明:第一个字符串的值下标为0,最后一个字符串的下标为-1;采用切片[:]方式选取字符时,注意是取头不取尾。

3.2 字符串拼接

>>> a='Hello'
>>> b='world'
>>> c=a+b
>>> c
'Helloworld'
d=a+' '+b
d
'Hello world'

说明:可以直接用加号来拼接字符串

3.3 通过字符串内建函数进行大小写转换

>>> a='Python'
>>> a.upper()
'PYTHON'
>>> a.lower()
'python'

注意:字符串中的元素可以索引,但是不能修改!


Comments

Make a comment