Python字符串学习笔记

简介: Python字符串学习笔记

一、字符串编码转换

1.1 使用encode()方法编码

       在Python中,字符串默认是以Unicode编码存储的,如果需要将字符串转化为其他编码格式,可以使用encode()方法。例如:

```
str = "你好"
encoded_str = str.encode("utf-8")
print(encoded_str)
```

1.2 使用decode()方法编码

       如果我们想将其他编码格式的字符转换为Unicode编码,可以使用decode()方法。例如:

```
encoded_str = b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_str = encoded_str.decode("utf-8")
print(decoded_str)
```

`

二、字符串常用操作

2.1 拼接字符串

       拼接字符串是指多个字符串连接在一起,形成一个新的字符串。可以使用“+”操作符或者使用join()方法。例如:

```
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)
# 使用join()方法
str_list = ["Hello", "World"]
concatenated_str = " ".join(str_list)
print(concatenated_str)
```

2.2 计算字符串长度

       可以使用len()方法来计算字符串的长度。例如:

```
str = "Hello World"
length = len(str)
print(length)
```

2.3 截取字符串

       截取字符串指的是从一个字符串中取出其中的一部分字符串。可以使用切片的方式来实现。例如:

```
str = "Hello World"
substring = str[6:11]
print(substring)
```

2.4 分割、合并字符串

       分割字符串指的是将一个字符串按照指定的分隔符拆分成多个子字符串。可以使用split()实现。例如:

```
str = "Hello,World"
splitted_str = str.split(",")
print(splitted_str)
# 合并字符串
str_list = ["Hello", "World"]
joined_str = ",".join(str_list)
print(joined_str)
```

2.5 检索字符串

       检索字符指的是寻找字符中是否包含某个字串,并返回该字串的位置或出现次数。可以使用in关键在或者find()、index()方法实现。例如:

```
str = "Hello World"
is_contained = "Hello" in str
print(is_contained)
# find()方法
index = str.find("World")
print(index)
# index()方法
index = str.index("World")
print(index)
```

2.6 字母的大小写转换

       可以使用upper()方法将字符串中的字母转换为大写,使用lower()方法将字符串中的字母转换为小写。例如:

```
str = "Hello World"
upper_str = str.upper()
print(upper_str)
lower_str = str.lower()
print(lower_str)
```

2.7 去除字符串中的空格和特殊字符

       可以使用strip()方法去除字符串两端的空格,可以使用replace()方法替换指定的字符串。例如:

```
str = "   Hello World   "
trimmed_str = str.strip()
print(trimmed_str)
replaced_str = str.replace("World", "Python")
print(replaced_str)
```

2.8 格式化字符串

       格式化字符串指的是将变量的值插入到字符中的占位符中。可以使用“+”操作符拼接字符串,也可以使用format()方法来实现。例如:

```
name = "Alice"
age = 25
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str)
# 可以使用位置参数
formatted_str = "My name is {1} and I am {0} years old.".format(age, name)
print(formatted_str)
# 可以使用关键字参数
formatted_str = "My name is {name} and I am {age} years old.".format(name="Alice", age=25)
print(formatted_str)
```

三、实践与练习

       在实践中,我们可以尝试使用字符串来解决具体的问题,比如字符串匹配、替换、分割等等。同时也可以通过练习来加深对字符串的理解和掌握。


练习:请编写一个程序,实现以下功能:


输入一个字符串,计算字符串中大写字母、小写字母、数字、空格和其他字符的个数。


将字符串中的所有大写字母转换为小写字母,将所有小写字母转换为大写字母,并输出转换后的字符串。

```python
def analyze_string(str):
    uppercase_count = 0
    lowercase_count = 0
    digit_count = 0
    space_count = 0
    other_count = 0
    for char in str:
        if char.isupper():
            uppercase_count += 1
        elif char.islower():
            lowercase_count += 1
        elif char.isdigit():
            digit_count += 1
        elif char.isspace():
            space_count += 1
        else:
            other_count += 1
    print("Uppercase letters count:", uppercase_count)
    print("Lowercase letters count:", lowercase_count)
    print("Digits count:", digit_count)
    print("Spaces count:", space_count)
    print("Other characters count:", other_count)
    transformed_str = str.swapcase()
    print("Transformed string:", transformed_str)
input_str = input("Please enter a string: ")
analyze_string(input_str)
```
相关文章
|
6天前
|
存储 索引 Python
Python学习笔记----列表、元组和字典的基础操作
这篇文章是一份Python学习笔记,涵盖了列表、元组和字典的基础操作,包括它们的创建、修改、删除、内置函数和方法等。
Python学习笔记----列表、元组和字典的基础操作
|
3天前
|
SQL JSON C语言
Python中字符串的三种定义方法
Python中字符串的三种定义方法
|
6天前
|
Python
Python学习笔记---函数
这篇文章是一份Python函数学习的笔记,涵盖了使用函数的优势、内置函数的调用、自定义函数的定义、函数参数的不同类型(必须参数、关键字参数、默认参数、可变参数)、有返回值和无返回值的函数、形参和实参、变量作用域、返回函数、递归函数、匿名函数、偏函数以及输入和输出函数等多个函数相关的主题。
|
6天前
|
索引 Python
Python学习笔记----操作字符串
这篇文章是一份Python字符串操作的学习笔记,涵盖了字符串相加、序列相加、字符串长度和字符的查找、统计、分割、连接、替换、去除空白、大小写转换以及判断字符串是否由字母和数字组成等常用方法。
Python学习笔记----操作字符串
|
6天前
|
Python
python学习笔记---流程控制
这篇文章详细介绍了Python中的流程控制,包括选择结构(if、if-else语句、嵌套if语句)和循环语句(while循环、for循环以及for循环与range()函数的使用),以及如何在循环中使用break和continue语句。
python学习笔记---流程控制
|
6天前
|
索引 Python
python学习笔记----必备知识
这篇文章是一份全面的Python学习笔记,涵盖了Python的必备知识,包括语法特点、流程控制、数据类型、运算符、输入输出方法,以及对序列、字符串、正则表达式、函数、面向对象程序设计、模块和包的介绍。
python学习笔记----必备知识
|
9天前
|
Python
2:Python字符串与数字
这段代码示例展示了Python中的字符串定义、字符串操作(如连接和重复)、基本算术运算以及条件判断。字符串可通过单双引号定义。字符串支持加法(连接)与乘法(重复)。数字变量支持加减乘除等运算。示例还对比了两个条件语句代码块:第一个因使用全角冒号及未闭合字符串引发语法错误;第二个则正确无误,当条件为真时将输出"我是神仙"和"我是高手"。这强调了遵循Python语法规范的重要性。
|
19天前
|
IDE API 开发工具
|
1月前
|
存储 Python 容器
Python基础语法:变量和数据类型详解(整数、浮点数、字符串、布尔值)
变量和数据类型是Python编程的基础,理解这些概念对于编写高效和正确的代码至关重要。通过本文的介绍,希望你能对Python中的变量和常用数据类型有一个清晰的认识,并能够在实际编程中灵活运用这些知识。
|
5天前
|
存储 数据安全/隐私保护 索引
Python基础语法day02字符串详解和列表
Python基础语法day02字符串详解和列表