字符串string
字符串的常见操作
#字符串可用单引号或双引号括起来声明,两种选择使得我们能够在字符串中包含单引号或者双引号——当字符串里有单引号时,外侧可使用双引号以保留里面的单引号原样,同理,当字符串里面需要包含双引号时,外侧可使用单引号
word="what's your name"
print(word)
what's your name
word='i told my friend "python is my fav language"'
print(word)
i told my friend "python is my fav language"
#使用转义符\'输出单个单引号
word='what\'s your name'
print(word)
what's your name
#防止转义符出错——使用原始字符串 r'...'
#比如我想表示一个c盘的目录
path='c:\abc\xyz.txt'
File "<input>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 6-7: truncated \xXX escape
#报错的原因就在于python看到\就认为是一个转义符 就把\和后面的a匹配起来了 但python中确实有\a这个转义符
#方法一:使用\\转义符表示\
path='c:\\abc\\xyz.txt'
print(path)
'c:\\abc\\xyz.txt'
#方法二:使用原始字符串——忽略转义标记,写入什么就输出什么
path=r'c:\abc\xyz.txt'
print(path)
'c:\\abc\\xyz.txt'
#计算字符串的长度——len()
name='tom'
len(name)
3
#字符串的合并拼接——使用加号+
first_name='ada'
last_name='hadid'
full_name=first_name+' '+last_name
message='good morning, '+full_name.title()+'!'
print(message)
good morning, Ada Hadid!
#字符串的重复打印——乘法符号*
'ok'*5
'okokokokok'
#使用for循环遍历字符串
s='hello'
for x in s:
print(x)
h
e
l
l
o
#print()会在每一个打印结果后面默认加上\n,如果希望以逗号或其他符号分隔开:
e "help", "copyright", "credits" or "license" for more information.
>>> s='hello'
>>> for x in s:
... print(x,end='!')
...
h!e!l!l!o!>>>
#查看字符串里的元素
>>> s='hello'
>>> s[0]
'h'
#字符串的切割——“左开右闭”,即包含切片区间左边下标索引值,不包含右边下标索引值。
s='abcdefg'
s[0:4]
'abcd'
s[1:3]
'bc'
#得到最后一个元素
#方法一:下标索引[-1]永远表示最后一个元素
s='abcdefg'
s[-1]
'g'
#方法二:长度减一就是最后一个元素的下标索引
s='abcdefg'
s[len(s)-1]
'g'
#从头到尾完整取出字符串——[:]
s='abcdefg'
s[:]
'abcdefg'
#步长值——间断跳跃取值
s='abcdefg'
s[::2]
#:表示全取 :2表示步长值为2
'aceg'
s='abcdefghijklmnopqrstuvwxyz'
s[0:8:2]
'aceg'
#0:8表示把下标为01234567对应的字母取出来 即第12345678个字母即abcdefgh取出来 然后:2表示步长值为2
#字符串的反转
h='hello'
h[::-1]
'olleh'
#使用ord()查询某个字符在阿斯克码表里的位置
ord('c')
99
#使用chr()查询阿斯克码表某个位置对应的字符
chr(99)
'c'
#字符串不支持原位改变
s='apple'
s[len(s)-1]='y'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
#如果仅仅是调用字符串的replace(),返回结果虽然是apply 但是变量s依旧是apple没改变。原因就在于字符串不支持原位改变
s.replace('e','y')
'apply'
s
'apple'
#所以要想把s变成apply,需要对s重新赋值
s=s.replace('e','y')
print(s)
apply
#方法 .title() ——以首字母大写的方式显示每个单词
name='mike jordan'
print(name.title())
Mike Jordan
#全部大写——.upper() 全部小写—— .lower()
name='mike jordan'
print(name.upper())
MIKE JORDAN
name='ARIANNA'
name.lower()
'arianna'
#删除字符串末尾的空白——.rstrip() 删除字符串开头的空白——.lstrip() 同时删除字符串两端的空白—— .strip()
s=' hello '
s
' hello '
s.strip()
'hello'
s.lstrip()
'hello '
s.rstrip()
' hello'
#注意 上述方法的改变仅仅是暂时的,再次访问变量时它依旧是原样——因为字符串不支持原位改变!——所以要想永久改变,需要重新赋值!
s=s.strip()
s=s.lstrip()
s=s.rstrip()
s=s.upper()
s=s.lower()
s=s.title()
#常用的添加空白的转义符——制表符\t 换行符\n
print('language:\n\tPython\n\tC\n\tJavaScript')
#\n使其换到下一行 \t使其在每一行开头添加一个制表符
language:
Python
C
JavaScript
#使用str()函数将非字符串值转换成字符串类型
age=23
message='Happy '+age+'rd Birthday!'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: must be str, not int
#字符串的拼接只能是字符串与字符串 而age变量是int型 所以会引发类型错误TypeError
message='Happy '+str(age)+'rd Birthday!'
print(message)
Happy 23rd Birthday!
#字符串与列表的相互转换
s = 'codeclassroom.com'
#使用list()将字符串转换成列表 这样子就可以对其元素进行修改
l=list(s)
l
['c', 'o', 'd', 'e', 'c', 'l', 'a', 's', 's', 'r', 'o', 'o', 'm', '.', 'c', 'o', 'm']
l[-1]='m'
l
['c', 'o', 'd', 'e', 'c', 'l', 'a', 's', 's', 'r', 'o', 'o', 'm', '.', 'c', 'o', 'm']
#使用.join()将列表里的元素拼接起来形成一个新的字符串赋值给x
x=''.join(l)
x
'codeclassroom.com'
#如果想以某一个符号分隔开各元素
z='!'.join(l)
z
'c!o!d!e!c!l!a!s!s!r!o!o!m!.!c!o!m'
#字符串.split()
name='kylie,kim,kendall'
#字符串name里的三个名字都以逗号分隔开,如果想把其中的名字取出来,可以使用.split()指定以某个字符分割
name.split(',')
#此时就会把字符串以逗号分隔出一个列表,列表中的元素就是字符串中以逗号分隔开的不包含逗号的三个元素
['kylie', 'kim', 'kendall']
#把.split()后的结果赋值给l
l=name.split(',')
l
['kylie', 'kim', 'kendall']
#此时就可以对列表中的元素进行修改
l[0]='gigi'
l
['gigi', 'kim', 'kendall']
name2=','.join(l)
name2
'gigi,kim,kendall'
#检查字符串是否以...开头/结尾—— 字符串.startswith()/字符串.endswith()
url='uke.cc'
url.startswith('http://')
False
url.startswith('u')
True
url.endswith('cc')
True
url.endswith('com')
False
#判断字符串里面是否包含某个子字符串——字符串.find('str',beg,end)beg指定从哪个索引开始 end指定到哪个索引结束 如果不指定则默认beg=0 end等于字符串长度 如果指定范围内包含子字符串则返回其下标索引 如果不包含则返回-1
major='finance'
major.find('f')
0
major.find('x')
-1
major.find('n',3,5)
4
major.find('a',4,6)
-1
#格式化字符串
a,b,c=1,2,3
'{1}=>{0}=>{2}'.format(a,b,c)
'2=>1=>3'
#占位符内声明索引下标,表明第一个a传给{0},第二个b传给{1},第三个c传给{2}
#如果占位符{}内不声明索引下标,则默认按顺序传递
a,b=1,2
'{}=>{}'.format(a,b)
'1=>2'
#也可以在占位符内{}写明变量名
'{name}=>{salary}'.format(name='tom',salary='9000')
'tom=>9000'
字符串常见操作总结
当字符串里有单引号时,外侧可使用双引号以保留里面的单引号原样,同理,当字符串里面需要包含双引号时,外侧可使用单引号
word=“what’s your name”
print(word)
what’s your name
word=‘i told my friend “python is my fav language”’
print(word)
i told my friend “python is my fav language”
防止误判转义符——使用原始字符串 r’…'使之忽略转义标记写入什么就输出什么
path=r’c:\abc\xyz.txt’
print(path)
‘c:\abc\xyz.txt’
计算字符串的长度——len()
len(‘string’)
使用加号+来合并拼接字符串
*字符串的重复打印——乘法符号 **
‘ok’*5
‘okokokokok’
使用for循环遍历字符串
s=’…’
for x in s:
print(x,end=‘希望显示的分割符号’)
使用下标索引查看字符串里的元素
s=’…’
s[0/1/2/3/…]
字符串的切割——“左开右闭”
s=‘abcdefg’
s[0:4]
‘abcd’
得到最后一个元素——方法一:下标索引[-1]永远表示最后一个元素 / 方法二:最后一个元素的下标索引为字符串长度减一
s[-1] / s[len(s)-1]
从头到尾完整取出字符串——[:]
s=‘abcdefg’
s[:]
‘abcdefg’
步长值 [:数值 ]——间断跳跃取值
s=‘abcdefghijklmnopqrstuvwxyz’
s[0:8:2]
‘aceg’
字符串的反转
s[::-1]
使用ord()查询某个字符在阿斯克码表里的位置/使用chr()查询阿斯克码表某个位置对应的字符
ord(’…’) / chr(数值)
.title()——以首字母大写的方式显示每个单词
.upper()——全部大写
.lower() ——全部小写
.strip()——同时删除字符串两端的空白
.lstrip()——删除字符串开头的空白
.rstrip()——删除字符串末尾的空白
.replace(’…’,’…’)——替换字符串中的某一个元素
s=‘apple’
s.replace(‘e’,‘y’)
‘apply’
字符串不支持原位改变,如果需要永久改变,需要重新赋值
s=s.replace()
s=s.strip()
s=s.lstrip()
s=s.rstrip()
s=s.title()
s=s.upper()
s=s.lower()
常用的添加空白的转义符——制表符\t 换行符\n
使用函数str()转换成字符串类型
使用 ’ '.join() 将列表里的元素拼接起来形成一个字符串
str=’’.join(list)
str=‘分隔字符’.join(list)
使用 字符串.split('分隔符’)将字符串以指定分隔符分割成一个列表
list=str.split(‘分隔符’)
检查字符串是否以…开头/结尾—— 字符串.startswith()/字符串.endswith()
判断字符串里面是否包含某个子字符串——字符串.find(‘str’,beg,end)若包含则返回下标索引 若不包含则返回-1
格式化字符串
‘{}’.format()