迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在Python 中拆分一个字符串,将其反转并重新连接

作者:迹忆客 最近更新:2023/01/14 浏览次数:

Python 中要拆分字符串,将其反转并重新连接:

  1. 使用 str.split() 方法将字符串拆分为列表。
  2. 使用 list.reverse() 方法反转列表的元素。
  3. 使用 str.join() 方法将列表连接成一个字符串。
my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

my_list.reverse()
print(my_list)  # 👉️ ['four', 'three', 'two', 'one']

my_str_again = ' '.join(my_list)
print(my_str_again)  # 👉️ four three two one

Python 中拆分一个字符串将其反转并重新连接

第一步是使用 str.split() 方法将字符串拆分为列表。

我们使用空格作为分隔符,但我们可以使用任何其他分隔符(例如逗号或连字符)。

str.split() 方法使用定界符将字符串拆分为子字符串列表。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

该方法采用以下 2 个参数:

  • separator 在每次出现分隔符时将字符串拆分为子字符串
  • maxsplit 最多完成 maxsplit 拆分(可选)

下一步是使用 list.reverse() 方法反转列表的元素。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

my_list.reverse()
print(my_list)  # 👉️ ['four', 'three', 'two', 'one']

list.reverse() 方法原地反转列表的元素。

该方法返回 None 因为它改变了原始列表。

如果我们不想就地改变原始列表,请使用步长为 -1 的列表切片语法。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

reversed_list = my_list[::-1]

print(reversed_list)  # 👉️ ['four', 'three', 'two', 'one']
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

我们没有为 startstop 指定值,但为 step 指定 -1 以获得新的反向列表。

最后一步是使用 str.join() 方法将反向列表连接成一个字符串。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

my_list.reverse()
print(my_list)  # 👉️ ['four', 'three', 'two', 'one']

my_str_again = ' '.join(my_list)
print(my_str_again)  # 👉️ four three two one

str.join 方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。

我们使用空格分隔符加入列表,但我们可以使用任何其他分隔符。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

my_list.reverse()
print(my_list)  # 👉️ ['four', 'three', 'two', 'one']

my_str_again = ','.join(my_list)
print(my_str_again)  # 👉️ four,three,two,one

如果我们不需要分隔符而只想将列表的元素连接到一个字符串中,请对空字符串调用 join() 方法。

my_str = 'one two three four'

my_list = my_str.split(' ')
print(my_list)  # 👉️ ['one', 'two', 'three', 'four']

my_list.reverse()
print(my_list)  # 👉️ ['four', 'three', 'two', 'one']

my_str_again = ''.join(my_list)
print(my_str_again)  # 👉️ fourthreetwoone

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便