python基础笔记2-字符串处理函数

  1. '', "", ''' ''', """ """ 都可以定义字符串,省略使用转义字符 '\'
>>> str1='hello'
>>> print str1
hello
>>> type(str1)
<type 'str'>
>>> str2='j'
>>> print str2
j
>>> type(str2)
<type 'str'>
>>> str3="word"
>>> print str3
word
>>> type(str3)
<type 'str'>
>>> str4='''hello world'''
>>> print str4
hello world
>>> type(str4)
<type 'str'>
>>> str5="""hell"""
>>> print str5
hell
>>> type(str5)
<type 'str'>
>>> print str3
xiao
>>> print str2
j
>>> print str2+str3
jxiao
>>> print str2*10
jjjjjjjjjj
>>> 'j' in str2
True
>>> 'j' in str3
False
>>> 'j' not in str3
True
>>> print 'hello\n\n\n'
hello



>>> print r'hello\n\n\n'  #r 使字符原始输出
hello\n\n\n
>>> 

python字符串格式化

>>> print 'my name is %s and weightis %d' % ('cpp', 2)   # %
my name is cpp and weightis 2  
>>> mystr='hello world itcast and itcastcpp'
>>> mystr.find('itcast')
12
>>> mystr[12:]
'itcast and itcastcpp'
>>> mystr.find('itcast',15) #15表示find的起始位置
23
>>> mystr[23:]
'itcastcpp'
>>> help(mystr.find) #帮助help函数查看find函数使用方法


>>>> mystr.index('xxx') #找不到会抛出异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> mystr.find('xxx') #找不到会显示-1
-1
>>> mystr.decode(encoding='UTF-8') #解码
u'hello world itcast and itcastcpp'
>>> s2=mystr.decode(encoding='UTF-8')
>>> type(s2)
<type 'unicode'>
>>> type(mystr)
<type 'str'>
>>> mystr.replace('itcast','jing') #字符串替换
'hello world jing and jingcpp'
>>> mystr = mystr.replace('itcast','xx',1)  #替换多少个
>>> mystr  # S.replace(old, new[, count]) -> string
'hello world xx and itcastcpp'
>>> 


>>> help(mystr.split)
>>> mystr.split(' ')
['hello', 'world', 'itcast', 'and', 'itcastcpp']
>>> arr = mystr.split(' ')
>>> for key in arr:
... print key
  File "<stdin>", line 2
    print key
        ^
IndentationError: expected an indented block
>>> for key in arr:
...     print key
... 
hello
world
itcast
and
itcastcpp


>>> arr = mystr.split(' ',2) #分割的列表的最后元素的下标
>>> print arr
['hello', 'world', 'itcast and itcastcpp']


>>> mystr.capitalize() #首字母大写
'Hello world itcast and itcastcpp'
>>> mystr.center(50/width)  #字符串居中,且距离两边的长度width
'         hello world itcast and itcastcpp         '
>>> mystr.center(80)
'                        hello world itcast and itcastcpp                        '


>>> mystr.endswith('itcast') #以字符串单词结尾
False
>>> mystr.endswith('itcastcpp')
True
>>> mystr.startswith('hello') #以字符串单词开始
True
>>> 


>>> mystr.isalnum()  #所有字符是数字或者字符为true否则为false
False
>>> mystr   #含有空格
'hello world itcast and itcastcpp'
>>> s='hello'
>>> s.isalnum()
True
>>> s='231231231'
>>> s.isalnum()
True
>>> s='231231231 '   #含有空格,所以false
>>> s.isalnum()
False


>>> s='healdf '
>>> s.isalpha()  #至少都是字符并且其他都是字母(不包含数字或者空格)则返回true 否则返回false
False
>>> s='healdf'
>>> s.isalpha()
True
>>> s='healdf23123'
>>> s.isalpha()
False


>>> s.isdigit() #只包含数字返回true否则返回false
False 
>>> s='213123'
>>> s.isdigit()
True


>>> s.islower()
False
>>> s='fsdfsdf'
>>> s.islower()
True
>>> s='fsdfsdF'
>>> s.islower()  #全部是小写
False
>>> s.isupper()  #全部是大写
False
>>> s='FSADFAS'
>>> s.isupper()
True


>>> s='   ' 
>>> s.isspace()  #只包含空格
True
>>> s='   1' 
>>> s.isspace()
False

>>> s='  healfk'
>>> s.lstrip()   #去除左空格
'healfk'
>>> s='  healfk   '
>>> s.lstrip()  
'healfk   '
>>> s.rstrip()   #去除右空格
'  healfk'
>>> s.strip()    #去除左右空格
'healfk'


>>> mystr.partition('it'/str)  #把mystr以str分割为三部分
('hello world ', 'it', 'cast and itcastcpp')
>>> mystr.partition('itcast')
('hello world ', 'itcast', ' and itcastcpp')
>>> mystr.partition('world')
('hello ', 'world', ' itcast and itcastcpp')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是第八篇笔记。 ### Python 文件操作 #### 文件操作基础 - 文件操作是指对计算机硬盘上的文件进行读写操作,Python 中的文件操作是通过内置的 `open()` 函数实现的。 - `open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)` 函数用于打开一个文件,并返回文件对象。 - `file`:要打开的文件名(包含路径)。 - `mode`:文件打开的模式,有读模式('r')、写模式('w')、追加模式('a')等。 - `buffering`:缓冲区大小,0 表示不缓冲,1 表示缓冲一行,大于 1 表示缓冲区大小,负数表示使用默认缓冲区大小。 - `encoding`:文件编码格式。 - `errors`:错误处理方式。 - `newline`:换行符。 - 文件对象的方法: - `read(size=-1)`:读取文件内容,`size` 表示读取的字节数,不指定表示读取整个文件内容。 - `readline(size=-1)`:读取文件中的一行内容,`size` 表示读取的字节数,不指定表示读取整行内容。 - `readlines(hint=-1)`:读取所有行并返回一个列表,`hint` 表示读取的字节数,不指定表示读取全部行。 - `write(string)`:将字符串写入文件。 - `writelines(sequence)`:将字符串序列写入文件,序列中每个元素都是字符串。 #### 文件操作示例 - 打开文件:`file = open('file_name', 'r')`。 - 读取文件内容:`content = file.read()`。 - 关闭文件:`file.close()`。 - 读取文件中的一行内容:`line = file.readline()`。 - 逐行读取文件内容:`for line in file: print(line)`。 - 写入文件内容:`file.write('Hello World!')`。 - 写入多行内容:`file.writelines(['Hello', 'World', '!'])`。 #### 文件操作进阶 - 使用 `with` 语句可以自动关闭文件,避免忘记关闭文件而导致的问题。 - 示例: ```python with open('file_name', 'r') as file: content = file.read() ``` - 使用 `os` 模块可以对文件进行更加高级的操作,如文件重命名、删除等。 - 示例: ```python import os os.rename('file_name', 'new_file_name') # 重命名文件 os.remove('file_name') # 删除文件 ``` ### Python 面向对象编程 #### 面向对象编程基础 - 面向对象编程是一种编程思想,将程序中的对象看作是相互交互的实体,通过它们之间的交互来完成程序的功能。 - 类(class)是面向对象编程中的一个重要概念,它是一种用户自定义的数据类型。 - 类中包含属性(特征)和方法(行为),属性指对象的数据成员,方法指对象的行为成员。 - 类的定义: ```python class ClassName: # 类属性 attribute = value # 构造函数 def __init__(self, arg1, arg2, ...): self.arg1 = arg1 self.arg2 = arg2 ... # 类方法 def method(self, arg1, arg2, ...): ... ``` - 类的实例化: ```python object_name = ClassName(arg1, arg2, ...) ``` - 对象的属性和方法: ```python object_name.attribute # 访问对象的属性 object_name.method(arg1, arg2, ...) # 调用对象的方法 ``` #### 面向对象编程示例 - 示例:定义一个 `Rectangle` 类,实现矩形的面积和周长计算。 ```python class Rectangle: # 类属性 name = 'Rectangle' # 构造函数 def __init__(self, width, height): self.width = width self.height = height # 类方法 def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) ``` - 使用示例: ```python rectangle = Rectangle(3, 4) print(rectangle.name) # 输出 'Rectangle' print(rectangle.area()) # 输出 12 print(rectangle.perimeter()) # 输出 14 ``` ### 总结 本篇笔记介绍了 Python 中的文件操作和面向对象编程基础,包括文件操作函数的使用、类的定义、对象的实例化和属性、方法的访问等。了解和掌握这些内容可以帮助我们更好地进行 Python 编程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值