python笔记-string

String Methods

Here are some of the most common string methods. A method is like a function, but it runs “on” an object. If the variable s is a string, then the code s.lower() runs the lower() method on that string object and returns the result (this idea of a method running on an object is one of the basic ideas that make up Object Oriented Programming, OOP). Here are some of the most common string methods:

  • s.lower(), s.upper() – returns the lowercase or uppercase version of the string
  • s.strip() – returns a string with whitespace removed from the start and end
  • s.isalpha()/s.isdigit()/s.isspace()… – tests if all the string chars are in the various character classes
  • s.startswith(‘other’), s.endswith(‘other’) – tests if the string starts or ends with the given other string
  • s.find(‘other’) – searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  • s.replace(‘old’, ‘new’) – returns a string where all occurrences of ‘old’ have been replaced by ‘new’ 对原string不影响
  • s.split(‘delim’) – returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it’s just text. ‘aaa,bbb,ccc’.split(‘,’) -> [‘aaa’, ‘bbb’, ‘ccc’]. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
  • s.join(list) – opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. ‘—’.join([‘aaa’, ‘bbb’, ‘ccc’]) -> aaa—bbb—ccc

String Slices

这里写图片描述

String %

Python has a printf()-like facility to put together a string. The % operator takes a printf-type format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right (a tuple is made of values separated by commas, typically grouped inside parentheses):

 # % operator
  text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

The above line is kind of long – suppose you want to break it into separate lines. You cannot just split the line after the ‘%’ as you might in other languages, since by default Python treats each line as a separate statement (on the plus side, this is why we don’t need to type semi-colons on each line). To fix this, enclose the whole expression in an outer set of parenthesis – then the expression is allowed to span multiple lines. This code-across-lines technique works with the various grouping constructs detailed below: ( ), [ ], { }.

  # add parens to make the long-line work:
  text = ("%d little pigs come out or I'll %s and %s and %s" %
    (3, 'huff', 'puff', 'blow down'))
  • 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、付费专栏及课程。

余额充值