在 Python 中迭代字符串中的单词
Python 中遍历字符串中的单词:
-
使用
str.split()
方法将字符串拆分为单词列表。 -
使用
for
循环遍历列表。
my_str = 'My site is jiyik.com'
for word in my_str.split():
# My
# site
# is
# jiyik.com
print(word)
我们使用 str.split()
方法将字符串拆分为单词列表。
str.split()
方法使用分隔符将字符串拆分为子字符串列表。
my_str = 'My site is jiyik.com'
# 👇️ ['My', 'site', 'is', 'jiyik.com']
print(my_str.split())
当没有分隔符传递给
str.split()
方法时,它会将输入字符串拆分为一个或多个空白字符。
my_str = 'My site is jiyik.com'
# 👇️ ['My', 'site', 'is', 'jiyik.com']
print(my_str.split())
for word in my_str.split():
# My
# site
# is
# bobbyhadz.com
print(word)
即使示例中的字符串间距不均匀,我们仍然可以从 str.split()
中获得一个单词列表。
或者,我们可以显式地将空格传递给 str.split()
方法。
my_str = 'My site is jiyik.com'
# 👇️ ['My', 'site', 'is', 'jiyik.com']
print(my_str.split(' '))
for word in my_str.split(' '):
# My
# site
# is
# jiyik.com
print(word)
现在字符串在每次出现空格时被拆分为一个列表。
如果我们省略对
str.split()
方法的调用并直接迭代字符串,那么我们将迭代每个字符。
my_str = 'My site is jiyik.com'
for word in my_str:
# M
# y
#
# s
# i
# ...
print(word)
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。