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)
```
相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
353 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
475 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
4月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
362 0
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
316 92
|
4月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多