Python中的字符串操作

Python中的字符串操作

本文介绍了Python中的字符串操作。

您可以学习各种字符串操作,例如创建和连接字符串、搜索和替换等,并附有代码示例。

YouTube Video

Python中的字符串操作

在Python中有多种操作字符串的方法。以下是常用字符串操作的介绍。

创建字符串

在Python中,字符串可以使用单引号(')、双引号(")或三引号('''""")来创建。

1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)
  • 此代码演示了如何在 Python 中使用单引号、双引号和三引号来创建和显示字符串。

字符串连接

要连接字符串,可以使用+运算符、f-stringsstr.format方法。

 1# + operator
 2name = "John"
 3greeting = "Hello, " + name + "!"
 4print(greeting)
 5
 6# f-string (available in Python 3.6 and above)
 7greeting_f = f"Hello, {name}!"
 8print(greeting_f)
 9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)
  • 此代码展示了如何在 Python 中使用 + 运算符、f-string 和 str.format 方法来连接字符串。

重复字符串

要重复字符串,可以使用*运算符。

1repeat = "ha" * 3  # Result: "hahaha"
2print(repeat)
  • 此代码演示了如何在 Python 中使用 * 运算符来重复字符串。

字符串的长度

要获取字符串的长度,可以使用len函数。

1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)
  • 此代码展示了如何在 Python 中使用 len 函数获取字符串的长度。

索引和切片

使用索引或切片可以获取字符串中的特定字符或子字符串。

 1word = "Python"
 2
 3first_char = word[0]    # P
 4last_char = word[-1]    # n
 5print(first_char)
 6print(last_char)
 7
 8# Slice
 9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)
  • 此代码演示了如何在 Python 中使用索引和切片来获取字符串中的特定字符或子串。

处理每个字符

由于字符串被视为序列类型,可以使用 for 循环处理每个字符。

1text = "Python"
2
3# Iterate each character
4for char in text:
5    print(char)
  • {^ i18n_speak このコードは、文字列 Python を1文字ずつ取り出して順番に表示する方法を示しています。^}

在字符串中搜索和替换

使用str.findstr.replace方法在字符串中进行搜索和替换。

1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)
  • 此代码展示了如何在 Python 中使用 str.find 方法查找字符串,并使用 str.replace 方法替换字符串。

转换字符串大小写

要将字符串转换为大写或小写,可以使用str.upperstr.lowerstr.capitalizestr.title

 1text = "hello world"
 2upper_text = text.upper()       # "HELLO WORLD"
 3lower_text = text.lower()       # "hello world"
 4capitalized_text = text.capitalize() # "Hello world"
 5title_text = text.title()       # "Hello World"
 6
 7print(upper_text)
 8print(lower_text)
 9print(capitalized_text)
10print(title_text)
  • 此代码演示了如何在 Python 中将字符串转换为大写、小写和标题格式。

分割和连接字符串

要按特定分隔符分割字符串,可以使用str.split;要连接列表中的元素,可以使用str.join

1csv = "apples,bananas,cherries"
2fruits = csv.split(",")  # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits)  # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)
  • 此代码展示了如何在 Python 中使用 str.split 拆分字符串,并使用 str.join 合并列表元素。

去除空格

要去除字符串中的空格,可以使用str.stripstr.lstripstr.rstrip

1whitespace = "   hello   "
2stripped = whitespace.strip()   # "hello"
3lstripped = whitespace.lstrip() # "hello   "
4rstripped = whitespace.rstrip() # "   hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)
  • 此代码演示了如何在 Python 中使用 str.stripstr.lstripstr.rstrip 删除字符串两端或任一端的空白。

总结

通过组合这些操作,可以在Python中执行各种字符串操作。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video