【100天精通python】Day22:字符串常用操作大全

目录

 专栏导读 

 一、 字符串常用操作

1 拼接字符串

2 计算字符串长度

3 截取字符串

4 分割合并字符串

5 检索字符串

6 字母的大小写转换

7 去除字符串的空格和特殊字符

8 格式化字符串

 二 、字符串编码转换

2.1 使用encode()方法编码

2.2 使用decoder()方法编码


 专栏导读 

专栏订阅地址:https://blog.csdn.net/qq_35831906/category_12375510.html


 一、 字符串常用操作

1 拼接字符串

使用 “ +”运算符将多个字符串拼接在一起。

示例:

string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)  # Output: "Hello World"

2 计算字符串长度

可以使用len()函数来计算字符串的长度,即其中字符的个数。

string = "Hello, Python!"
length = len(string)
print(length)  # Output: 15

3 截取字符串

使用切片操作截取字符串的一部分。

string = "Hello, Python!"
substring = string[0:5]
print(substring)  # Output: "Hello"

4 分割合并字符串

使用split()方法可以将一个字符串按照指定的分隔符分割成多个部分。使用join()方法可以将多个字符串合并成一个。

string = "apple,orange,banana"
fruits_list = string.split(",")
print(fruits_list)  # Output: ['apple', 'orange', 'banana']

fruits = "-".join(fruits_list)
print(fruits)  # Output: "apple-orange-banana"

5 检索字符串

使用find()方法或index()方法来检索子字符串在原字符串中的位置。

find()方法会返回第一次出现的位置,如果没有找到则返回-1;而index()方法会在找不到子字符串时抛出异常。

string = "Hello, Python!"
position1 = string.find("Python")
print(position1)  # Output: 7

position2 = string.index("World")  # Raises ValueError: substring not found

6 字母的大小写转换

 Python中有几个方法可以实现字母的大小写转换。upper()方法将所有字母转换为大写,lower()方法将所有字母转换为小写,capitalize()方法将首字母转换为大写。

string = "Hello, Python!"
upper_string = string.upper()
lower_string = string.lower()
capitalized_string = string.capitalize()

print(upper_string)  # Output: "HELLO, PYTHON!"
print(lower_string)  # Output: "hello, python!"
print(capitalized_string)  # Output: "Hello, python!"

7 去除字符串的空格和特殊字符

        可以使用strip()方法去除字符串两端的空格(包括换行符等空白字符)。

        如果想去除指定字符,可以使用strip()方法的参数指定要去除的字符。

string = "   Hello, Python!   "
trimmed_string = string.strip()
print(trimmed_string)  # Output: "Hello, Python!"

string_with_special_chars = "!@#$Hello, Python!%^&*"
cleaned_string = string_with_special_chars.strip("!@#$%^&*") #去除指定字符
print(cleaned_string)  # Output: "Hello, Python!"

8 格式化字符串

        在Python中,你可以使用多种方式来格式化字符串。其中一种常用的方式是使用format()方法,它允许将变量的值插入到字符串中的占位符位置。

name = "Alice"
age = 30

# 使用位置参数插入
formatted_string1 = "My name is {} and I am {} years old.".format(name, age)

# 使用关键字参数插入
formatted_string2 = "My name is {n} and I am {a} years old.".format(n=name, a=age)

print(formatted_string1)  # Output: "My name is Alice and I am 30 years old."
print(formatted_string2)  # Output: "My name is Alice and I am 30 years old."

此外,还有一种更简洁的方式是使用f-string(格式化字符串字面值)。

示例:

name = "Alice"
age = 30

# 使用f-string
formatted_string = f"My name is {name} and I am {age} years old."

print(formatted_string)  # Output: "My name is Alice and I am 30 years old."

 二 、字符串编码转换

        在Python中,字符串编码转换涉及将字符串从一种字符编码格式转换为另一种字符编码格式。常见的字符编码格式包括UTF-8、ASCII、ISO-8859-1等。

2.1 使用encode()方法编码

        在Python中,字符串对象有一个encode()方法,可以将字符串转换为指定的字符编码格式。该方法返回一个字节对象(bytes类型)。

original_string = "Hello, 你好!"

# 将字符串编码为UTF-8格式
encoded_bytes = original_string.encode('utf-8')
print(encoded_bytes)  # Output: b'Hello, \xe4\xbd\xa0\xe5\xa5\xbd!'

# 将字符串编码为ASCII格式
encoded_bytes_ascii = original_string.encode('ascii', errors='ignore')
print(encoded_bytes_ascii)  # Output: b'Hello, !'

2.2 使用decoder()方法编码

        对于已经编码为字节对象(bytes类型)的字符串,我们可以使用decode()方法将其解码为指定的字符编码格式。

encoded_bytes = b'Hello, \xe4\xbd\xa0\xe5\xa5\xbd!'

# 将字节对象解码为UTF-8格式
decoded_string = encoded_bytes.decode('utf-8')
print(decoded_string)  # Output: "Hello, 你好!"

# 将字节对象解码为ASCII格式
decoded_string_ascii = encoded_bytes.decode('ascii', errors='ignore')
print(decoded_string_ascii)  # Output: "Hello, !"

         需要注意的是,在进行编码和解码时,要确保目标编码格式能够表示原始字符串中的所有字符,否则会出现异常。

        在使用encode()decode()方法时,可以指定一个errors参数来处理编码和解码过程中的错误。常见的errors参数值有:

  • 'strict'(默认值):如果出现非法字符,抛出UnicodeEncodeError(编码)或UnicodeDecodeError(解码)异常。
  • 'ignore':忽略非法字符,直接忽略它们。
  • 'replace':用Unicode Replacement Character(U+FFFD)替代非法字符。
  • 'xmlcharrefreplace':用XML字符引用替代非法字符。

要确保正确地处理不同编码之间的转换,需要了解原始字符串的编码格式以及目标编码格式,并根据需要选择合适的转换方式。通常情况下,推荐使用UTF-8编码,因为它能够表示几乎所有的字符,而且在多平台和多语言环境中广泛使用。


下一篇介绍正则表达式

猜你喜欢

转载自blog.csdn.net/qq_35831906/article/details/131983224