Python学习笔记2019-5-7am

Python运算符、语句及函数使用介绍
该博客主要介绍Python相关知识,涵盖算数、比较、赋值、成员等运算符,还介绍了break、continue、pass等重要语句,以及数据类型转换、range函数使用,同时提及大小写转换和反斜杠转义字符的处理方法。

1.算数运算符
取模:%(取余数)
幂:**
取整数://
2.比较运算符
<>
3.赋值运算符
=
+=
-=
*=
/=
%=
**=
//=
4.成员运算符
in 如果在指定的序列中找到值,则返回True,否则返回False
not in
5.重要语句
break:跳出for和while的循环体,不在执行循环
countiue:被用来告诉python跳出当前循环块中的剩余语句,然后继续执行下一轮循环
pass:占位符
6.数据类型转换
int(var)
7.range函数
range生成一个序列
range(10) :0到9,不包含10,step=1
range(3,10):3到9,不包含10,step=1
range(2,10,2):2到10,不包含10,step=2
8.大小写转换
name=‘python’
print(name.title())
首字母大写
print(name.lower())
全部小写
print(name.upper())
全部大写
9.反斜杠\转义字符
在引号外加r字母,意为取消转义字符

### Python字符串处理的相关学习笔记与示例 #### 字符串基础操作 Python提供了丰富的内置函数来支持字符串的操作,例如拼接、重复、查找和替换等。这些基本功能构成了日常开发中不可或缺的一部分[^1]。 ```python # 字符串拼接 str1 = "Hello" str2 = "World" result = str1 + " " + str2 # 使用加号进行拼接 print(result) # 输出: Hello World # 字符串重复 repeat_str = "abc" * 3 print(repeat_str) # 输出: abcabcabc # 查找子字符串的位置 position = result.find("World") print(position) # 输出: 6 # 替换字符串中的部分 new_result = result.replace("World", "Python") print(new_result) # 输出: Hello Python ``` --- #### 字符串格式化方法 除了简单的字符串操作外,Python还提供多种方式来进行字符串的格式化输出,其中包括 `.format()` 和 `f-string` 这两种常用的方法[^2][^4]。 ##### 使用 `.format()` 方法 `.format()` 是一种灵活且强大的工具,允许开发者通过占位符动态填充数据到模板字符串中。 ```python name = "Alice" age = 30 formatted_string = "Name: {}, Age: {}".format(name, age) print(formatted_string) # 输出: Name: Alice, Age: 30 # 自定义位置参数 custom_order = "{1} was born in the year {0}".format(1990, name) print(custom_order) # 输出: Alice was born in the year 1990 ``` ##### 使用 `f-string` 自 Python 3.6 起引入的 `f-string` 提供了一种更加简洁直观的方式来嵌入变量或表达式。 ```python greeting = f"Hello, my name is {name}. I am {age} years old." print(greeting) # 输出: Hello, my name is Alice. I am 30 years old. ``` --- #### 获取字符串长度 为了统计字符串中字符的数量,可以使用内置函数 `len()` 来完成这一任务。该函数不仅适用于字符串,还可以用于其他序列类型的对象,如列表、元组和字典[^3]。 ```python sample_text = "This is a sample text." length_of_text = len(sample_text) print(f"The length of the string is: {length_of_text}") # 输出: The length of the string is: 21 example_list = ["apple", "banana", "cherry"] list_length = len(example_list) print(list_length) # 输出: 3 ``` --- #### 高效字符串旋转 当涉及到字符串的旋转操作时,可以通过切片或者利用 `collections.deque` 的高效特性来实现[^5]。 ```python from collections import deque def rotate_string(s, n): d = deque(s) rotation_steps = n % len(s) if s else 0 d.rotate(-rotation_steps) return ''.join(d) original_string = "abcdef" rotated_string = rotate_string(original_string, 2) print(rotated_string) # 输出: cdefab ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值