python 字符串常用操作+yield的用法

本文展示了Python中字符串的find、count和replace方法的使用,如查找子串位置、计数和替换。同时,解释了yield在创建生成器函数中的作用,并给出了一个使用生成器和列表推导式生成偶数平方的例子。

1. 字符串find\count\replace

string = "abcdefgab"

print(string.find("ab"))
print(string.find("gg"))
print(string.count("ab"))
print(string.replace("aa", "ab"))
E:\pythonPrj\common\venv\Scripts\python.exe E:/pythonPrj/common/02-string.py
0
-1
2
abcdefgab

Process finished with exit code 0

2. yield用法

def function():
    for i in range(5):
        yield i
        yield i + 1


new_function = [x * x for x in function() if x % 2 == 0]
print(new_function)
for j in new_function:
    print(j, "")
E:\pythonPrj\common\venv\Scripts\python.exe E:/pythonPrj/common/03-yield.py
[0, 4, 4, 16, 16]
0 
4 
4 
16 
16 

Process finished with exit code 0
### 定义字符串变量 在 Python 中,字符串变量可以通过单引号 `' '` 或双引号 `" "` 来定义。字符串类型表示一系列字符的集合。例如: ```python s1 = "hello world!" s2 = 'Hello Python' ``` 字符串的定义可以灵活使用单引号或双引号,具体取决于字符串内部包含的字符。如果字符串中包含单引号,则建议使用双引号包裹字符串,反之亦然。如果字符串中同时包含单引号和双引号,则需要使用反斜杠 `\` 进行转义 [^2]。 ```python s3 = "It's a sunny day" s4 = 'He said, "Hello!"' s5 = "He said, \"Hello!\"" ``` ### 字符串的基本操作 Python 提供了多种字符串操作方法,例如大小写转换、字符串拼接、格式化等。 #### 字符串大小写转换 字符串的大小写转换可以用于格式化输出或数据存储。以下是常见的大小写转换方法: - `title()`:将每个单词的首字母大写。 - `upper()`:将字符串中所有字母转换为大写。 - `lower()`:将字符串中所有字母转换为小写 [^1]。 ```python s1 = "hello world!" s2 = s1.title() # 将每个单词的首字母大写 s3 = s1.upper() # 将单词的每一个字母均大写 s4 = s1.lower() # 将单词的每一个字母均小写 print(s1) # 输出: hello world! print(s2) # 输出: Hello World! print(s3) # 输出: HELLO WORLD! print(s4) # 输出: hello world! ``` #### 字符串拼接 字符串可以通过加号 `+` 进行拼接操作: ```python s6 = "Hello" s7 = "World" s8 = s6 + " " + s7 print(s8) # 输出: Hello World ``` #### 字符串格式化 Python 提供了多种字符串格式化方法,例如使用 `%` 运算符、`str.format()` 方法以及 f-string(Python 3.6+)。 ```python name = "Alice" age = 25 # 使用 % 运算符 print("Name: %s, Age: %d" % (name, age)) # 输出: Name: Alice, Age: 25 # 使用 str.format() print("Name: {0}, Age: {1}".format(name, age)) # 输出: Name: Alice, Age: 25 # 使用 f-string print(f"Name: {name}, Age: {age}") # 输出: Name: Alice, Age: 25 ``` ### 字符串的不可变性 Python 中的字符串是不可变数据类型,这意味着一旦字符串被创建,其内容不能被修改。任何对字符串的修改操作都会生成一个新的字符串对象: ```python s9 = "hello" s10 = s9 + " world" print(s9) # 输出: hello print(s10) # 输出: hello world ``` ### 字符串常用方法 Python 提供了许多内置方法来处理字符串,以下是一些常用方法: - `len()`:获取字符串的长度。 - `index()`:查找子字符串的索引位置。 - `split()`:将字符串按指定分隔符拆分为列表。 - `replace()`:替换字符串中的子字符串。 ```python s11 = "hello world" print(len(s11)) # 输出: 11 print(s11.index("o")) # 输出: 4 print(s11.split(" ")) # 输出: ['hello', 'world'] print(s11.replace("world", "Python")) # 输出: hello Python ``` ### 关键字和标识符 在定义字符串变量时,需要注意 Python 的关键字和标识符规则。Python 有 33 个关键字,这些关键字不能作为变量名使用。以下是 Python 的关键字列表 [^4]: ```python ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] ``` 变量名必须是有效的标识符,遵循以下规则: - 变量名必须以字母或下划线 `_` 开头。 - 变量名只能包含字母、数字和下划线。 - 变量名不能是 Python 的关键字。 ### 示例代码 以下是一个完整的示例,展示了字符串变量的定义和常见操作: ```python # 定义字符串变量 s1 = "hello world!" s2 = 'Hello Python' # 大小写转换 s3 = s1.title() s4 = s1.upper() s5 = s1.lower() # 字符串拼接 s6 = "Hello" s7 = "World" s8 = s6 + " " + s7 # 字符串格式化 name = "Alice" age = 25 print("Name: %s, Age: %d" % (name, age)) print("Name: {0}, Age: {1}".format(name, age)) print(f"Name: {name}, Age: {age}") # 不可变性 s9 = "hello" s10 = s9 + " world" # 常用方法 s11 = "hello world" print(len(s11)) print(s11.index("o")) print(s11.split(" ")) print(s11.replace("world", "Python")) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值