当前位置:   article > 正文

Python字符串操作详解(超详细)

python字符串操作

Python字符串操作详解

在这里插入图片描述

一. 字符串创建

  • Python中,字符串可以使用单引号、双引号或三重引号来创建。
  • 使用单引号或双引号创建的字符串是一行字符串。
  • 使用三重引号创建的字符串可以包含多行文本。
str1 = 'Hello, World!'  # 单引号
str2 = "Hello, World!"  # 双引号
str3 = '''Hello, World!'''  # 三重引号
str4 = """Hello, World!"""  # 三重引号
multiline_string = """This is a
multiline
string."""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
'
运行

二. 字符串拼接

1. 使用 + 运算符

最简单的方法是使用 + 运算符将两个字符串连接起来

str1 = "Hello, "
str2 = "World!"
result = str1 + str2
print(result)  # 输出: Hello, World!
  • 1
  • 2
  • 3
  • 4
'
运行

2. 使用 .join() 方法

  • 允许我们连接一个字符串列表或可迭代对象中的所有字符串。

  • 这种方法在处理大量字符串时通常更高效。

str_list = ["Hello", "World", "!"]
result = "".join(str_list)
print(result)  # 输出: HelloWorld!
  • 1
  • 2
  • 3
'
运行

在这个例子中,我们将 str_list 列表中的所有字符串连接起来,并且使用空字符串 "" 作为连接符。


三. 字符串索引和切片

1. 字符串索引

  • 在Python中,字符串中的每个字符都有一个索引,可以用来访问该字符。

  • 字符串的第一个字符的索引是 0,第二个字符的索引是 1,依此类推。例如:

s = "Hello, World!"
print(s[0])  # 输出: H
print(s[7])  # 输出: W
print(s[-1])  # 输出: !(负索引表示从末尾开始计数)
  • 1
  • 2
  • 3
  • 4
'
运行

2. 字符串切片

  • 切片使用 start:stop:step 的形式,其中 start 表示起始索引,stop 表示结束索引(不包括该索引对应的字符),step 表示步长(默认为1)。
s = "Hello, World!"
print(s[7:])    # 输出: World!(从索引7开始到结尾)
print(s[:5])    # 输出: Hello(从开头到索引5之前)
print(s[3:8])   # 输出: lo, W(从索引3到索引8之前)
print(s[::2])   # 输出: Hlo ol!(每隔一个字符取一个)
print(s[::-1])  # 输出: !dlroW ,olleH(反转字符串)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
'
运行

3. 字符串长度和负索引

  • len() 函数获取字符串的长度,同时也可以使用负索引来从末尾开始访问字符串。
s = "Hello, World!"
print(len(s))     # 输出: 13
print(s[-1])      # 输出: !(倒数第一个字符)
print(s[-3:])     # 输出: ld!(倒数第三个字符到结尾)
print(s[:-3])     # 输出: Hello, Wor(从开头到倒数第三个字符之前)
  • 1
  • 2
  • 3
  • 4
  • 5
'
运行

4. 字符串不可变性

  • 需要注意的是,字符串是不可变的,意味着不能直接修改字符串中的某个字符,但可以通过切片和拼接来达到类似的效果。
s = "Hello, World!"
# s[0] = 'h'  # 这会引发错误,字符串不可变
new_s = 'h' + s[1:]  # 使用切片和拼接来实现字符串的修改
print(new_s)  # 输出: hello, World!
  • 1
  • 2
  • 3
  • 4
'
运行

四. 字符串长度

s = "Hello, World!"
print(len(s))  # 输出: 13
  • 1
  • 2
'
运行

五. 字符串转换

  1. s.upper()

    • 该方法返回字符串的大写版本。
    • 示例:
      s = "hello"
      print(s.upper())  # 输出: HELLO
      
      • 1
      • 2
      '
      运行
  2. s.lower()

    • 该方法返回字符串的小写版本。
    • 示例:
      s = "HELLO"
      print(s.lower())  # 输出: hello
      
      • 1
      • 2
      '
      运行
  3. s.capitalize()

    • 该方法返回字符串的首字母大写版本,其余字母小写。
    • 示例:
      s = "hello"
      print(s.capitalize())  # 输出: Hello
      
      • 1
      • 2
      '
      运行
  4. s.title()

    • 该方法返回字符串中每个单词的首字母大写的版本。
    • 示例:
      s = "hello world"
      print(s.title())  # 输出: Hello World
      
      • 1
      • 2
      '
      运行

六. 查找子字符串

  1. find(substring, start, end) 方法:

    • find() 方法用于在字符串中查找子字符串 substring 第一次出现的位置,并返回其索引值。如果未找到子字符串,则返回 -1。
    • 可选参数 startend 可以指定查找子字符串的起始和结束位置。
    • 示例:
      s = "hello world"
      print(s.find("world"))   # 输出: 6
      print(s.find("python"))  # 输出: -1
      
      • 1
      • 2
      • 3
      '
      运行
  2. index(substring, start, end) 方法:

    • index() 方法与 find() 方法类似,用于在字符串中查找子字符串 substring 第一次出现的位置,并返回其索引值。如果未找到子字符串,则会抛出异常。
    • 可选参数 startend 可以指定查找子字符串的起始和结束位置。
    • 示例:
      s = "hello world"
      print(s.index("world"))   # 输出: 6
      # print(s.index("python"))  # 会抛出异常 ValueError: substring not found
      
      • 1
      • 2
      • 3
      '
      运行

七. 字符串替换

  • 在Python中,可以使用 replace() 方法来替换字符串中的特定子字符串。
  • 这个方法会创建一个新的字符串,其中指定的子字符串被替换为你提供的新字符串。
new_string = old_string.replace(old_substring, new_substring, count)
  • 1

其中:

  • old_string 是你要进行替换操作的原始字符串。
  • old_substring 是你想要替换的子字符串。
  • new_substring 是用来替换旧子字符串的新字符串。
  • count 是可选参数,用于指定替换的次数。如果提供了这个参数,只会替换前 count 次出现的子字符串。如果不提供 count 参数,则会替换所有出现的子字符串。
old_string = "I like apples, apples are delicious."
new_string = old_string.replace("apples", "oranges")
print(new_string)
  • 1
  • 2
  • 3
'
运行

输出:

I like oranges, oranges are delicious.
  • 1
  • 注意,replace() 方法不会修改原始字符串,而是返回一个新的替换后的字符串。

八. 字符串拆分

当处理文本数据时,经常需要将字符串按照某种规则进行拆分,以便进一步处理或分析。Python 中的 split() 方法就是用来完成这个任务的。

1. 基本用法

split() 方法可以基于指定的分隔符将一个字符串拆分成多个子字符串,并返回一个列表。其基本语法如下:

string.split(separator, maxsplit)
  • 1
  • string 是要拆分的原始字符串。
  • separator 是用于确定拆分位置的分隔符,默认为任何空白字符(空格、制表符、换行符等)。
  • maxsplit 是可选参数,用于指定拆分的最大次数。如果指定了 maxsplit 参数,最终的列表将包含至多 maxsplit+1 个元素。

2. 示例

假设有一个字符串表示一句英文句子:

sentence = "Hello, world! How are you today?"
  • 1
'
运行

我们可以使用空格作为分隔符,将这个句子拆分成单词:

words = sentence.split()
print(words)
# 输出: ['Hello,', 'world!', 'How', 'are', 'you', 'today?']
  • 1
  • 2
  • 3

还可以使用逗号作为分隔符,将句子拆分成短语:

phrases = sentence.split(",")
print(phrases)
# 输出: ['Hello', ' world! How are you today?']
  • 1
  • 2
  • 3

3. 注意事项

  • 如果字符串中不存在分隔符,split() 方法会返回包含原始字符串作为唯一元素的列表。
  • 如果字符串以分隔符开头或结尾,split() 方法会在结果列表中包含空字符串。
  • 如果要拆分的字符串中有连续的分隔符,那么会在结果列表中产生相应数量的空字符串。

4. 使用示例

s = "apple,banana,,orange,"
result = s.split(",")
print(result)
# 输出: ['apple', 'banana', '', 'orange', '']
  • 1
  • 2
  • 3
  • 4
'
运行

结果列表中有一个空字符串是因为连续的两个逗号之间没有其他内容,导致产生了一个空字符串元素。

九. 去除字符串首尾空格

  • strip() 是 Python 中用于移除字符串首尾指定字符(默认为空白字符)的方法。
  • 可以帮助我们清理字符串中不需要的空格、制表符、换行符等,使得字符串更加规范。

1. 基本用法

strip() 方法能够移除字符串首尾的指定字符(默认为空白字符),其基本语法如下:

string.strip([chars])
  • 1
  • string 是要处理的原始字符串。
  • chars 是可选参数,用于指定要移除的字符集合,默认为移除空白字符。

2. 示例

2.1 移除空白字符
s = "   hello, world!   "
result = s.strip()
print(result)
# 输出: 'hello, world!'
  • 1
  • 2
  • 3
  • 4
'
运行

在这个示例中,strip() 方法将字符串 s 首尾的空白字符移除了,返回了一个去掉空白的新字符串。

2.2 移除指定字符
s = "***hello, world!***"
result = s.strip("*")
print(result)
# 输出: 'hello, world!'
  • 1
  • 2
  • 3
  • 4
'
运行

strip("*") 方法将字符串 s 首尾的星号 * 移除了,返回了一个去掉星号的新字符串。

3. 注意事项

  • strip() 方法只会移除字符串开头和结尾的指定字符,不会对字符串中间的字符产生影响。
  • 如果指定了 chars 参数,strip() 方法会移除开头和结尾连续出现的 chars 中的字符,直到遇到非 chars 中的字符为止。

4. 使用示例

s = "+++hello+++world+++"
result = s.strip("+")
print(result)
# 输出: 'hello+++world'
  • 1
  • 2
  • 3
  • 4
'
运行

由于 strip("+") 方法只移除了开头和结尾的加号 +,所以中间的加号没有被移除。

十. 字符串判断

1. isalpha()

isalpha() 方法用于判断字符串是否只包含字母,如果字符串中至少有一个字符且所有字符都是字母,则返回 True,否则返回 False

s = "hello"
print(s.isalpha())  # 输出: True
  • 1
  • 2
'
运行

2. isdigit()

isdigit() 方法用于判断字符串是否只包含数字,如果字符串中至少有一个字符且所有字符都是数字,则返回 True,否则返回 False

s = "123"
print(s.isdigit())  # 输出: True
  • 1
  • 2
'
运行

3. islower()

islower() 方法用于判断字符串中的字母是否全部为小写,如果字符串中至少有一个字母且所有字母都是小写,则返回 True,否则返回 False

s = "hello"
print(s.islower())  # 输出: True
  • 1
  • 2
'
运行

4. isupper()

isupper() 方法用于判断字符串中的字母是否全部为大写,如果字符串中至少有一个字母且所有字母都是大写,则返回 True,否则返回 False

s = "HELLO"
print(s.isupper())  # 输出: True
  • 1
  • 2
'
运行

5. isspace()

isspace() 方法用于判断字符串是否只包含空格,如果字符串中至少有一个字符且所有字符都是空格,则返回 True,否则返回 False

s = "   "
print(s.isspace())  # 输出: True
  • 1
  • 2
'
运行

十一. 字符串格式化

1. 使用 % 运算符进行格式化

name = "Alice"
age = 25
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
  • 1
  • 2
  • 3
  • 4
'
运行

%s%d 是占位符,分别代表字符串和整数的位置。% 运算符后面的元组 (name, age) 包含了要插入到字符串中的值。

2. 使用 format() 方法进行格式化

name = "Bob"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
  • 1
  • 2
  • 3
  • 4
'
运行

{} 被用作占位符,format() 方法将括号中的值依次插入到字符串中。

另外,还可以使用 f-string 来进行字符串格式化:

name = "Carol"
age = 35
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
  • 1
  • 2
  • 3
  • 4
'
运行

字符串前面的 f 表示这是一个 f-string,花括号内的表达式会被求值并插入到字符串中。

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/917963
推荐阅读
相关标签
  

闽ICP备14008679号