Python学习笔记(3)-字符串

创建字符串

一对单引号或双引号

>>> 'hello world'

'hello world'

>>> "hello world"

'hello world'

可以字符串开始的引号之前加上r,忽略所有转义字符

三元引号,创建多行字符串,所有引号、制表符、换行都是字符串的一部分,可以作多行注释

>>> print('''

你好

    蔡威

     再见''')

 

你好

    蔡威

     再见

使用str()进行类型转换

可以将Python数据类型转换为字符串

拼接

>>> 'caiwei'+','+'hello'

'caiwei,hello'

复制

>>> '我爱你'*3

'我爱你我爱你我爱你'

提取字符,下标和切片

>>> a = 'helloworld'

>>> a[0]

'h'

>>> a[::2]

'hlool'

in 和 not in

>>> 'hello' in 'helloworld'

True

>>> 'caiwei' in 'helloworld'

False

字符串方法

长度len()

>>> len('hello')

大小写lower() upper()

所有字符都变成大写或小写

>>> 'HEllo'.lower()

'hello'

>>> 'HEllo'.upper()

'HELLO'

isX方法

islower() isupper()大小写

isalpha()字母

isalnum()数字和字母

isdecimal()数字

isspace()转义字符

判断开始或结束部分是否等于另一个字符串startswith() endswith()

>>> 'helloworld'.startswith('he')

True

>>> 'helloworld'.startswith('ll')

False

>>> 'helloworld'.endswith('world')

True

>>> 'helloworld'.endswith('he')

False

字符串和列表 join()和split()

>>> 'hello,world'.split(',')

['hello', 'world']

>>> ','.join(['hello', 'world'])

'hello,world'

对齐文本rjust(),ljust()和center()

第一个参数在这个字符串个数

第二个参数是指填充字符

>>> a.rjust(20,'*')

'**********helloworld'

>>> a.ljust(20,'*')

'helloworld**********'

>>> a.center(20,'*')

'*****helloworld*****'

删除空白字符lstrip() rstrip() strip()

可以设置参数,默认空格

>>> a = ' hello world '

>>> a.lstrip()

'hello world '

>>> a

' hello world '

>>> a.rstrip()

' hello world'

>>> a

' hello world '

>>> a.strip()

'hello world'

>>> a

' hello world '

替换 replace()

第一个参数是要修改字符串,

第二个参数是传入字符串

>>> a.replace('world','caiwei')

' hello caiwei '

复制粘贴字符串pyperclip模块

>>> import pyperclip as py

>>> py.copy('hello world')

>>> py.paste()

'hello world'

posted on 2017-11-07 15:19  威行天下  阅读(345)  评论(0编辑  收藏  举报

导航