在 Python 中计算字符串中的大写字母
Python 中要计算字符串中的大写字母:
- 使用生成器表达式迭代字符串。
-
使用
str.isupper()
方法检查每个字符是否为大写。 -
使用
sum()
函数获取大写字母的计数。
my_str = 'FQLjiyik123'
# ✅ 计算字符串中的大写字母
uppercase_count = sum(1 for char in my_str if char.isupper())
print(uppercase_count) # 👉️ 3
# -------------------------------------------------
# ✅ 从字符串中提取大写字母
only_upper = ''.join(char for char in my_str if char.isupper())
print(only_upper) # 👉️ FQL
我们使用生成器表达式来迭代字符串。
生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。
在每次迭代中,我们使用 str.isupper()
方法检查当前字符是否为大写,如果是则返回 1。
如果字符串中的所有大小写字符都是大写且字符串至少包含一个大小写字符,则 str.isupper
方法返回 True,否则返回 False。
my_str = 'JIYIK.COM'
# ✅ 检查字符串中的所有字符是否都是大写
all_uppercase = my_str.isupper()
print(all_uppercase) # 👉️ True
最后一步是使用 sum()
函数获取字符串中大写字母的总数。
my_str = 'FQLjiyik123'
uppercase_count = sum(1 for char in my_str if char.isupper())
print(uppercase_count) # 👉️ 3
sum
函数接受一个可迭代对象,从左到右对其项目求和并返回总数。
如果需要从字符串中提取大写字母,可以使用相同的方法。
my_str = 'FQLjiyik123'
only_upper = ''.join(char for char in my_str if char.isupper())
print(only_upper) # 👉️ FQL
only_upper = [char for char in my_str if char.isupper()]
print(only_upper) # 👉️ ['F', 'Q', 'L']
第一个示例使用 str.join()
方法将字符串中的大写字符连接到新字符串中。
第二个示例返回一个列表,其中包含字符串中的大写字符。
或者,我们可以使用简单的 for 循环。
使用 for 循环计算字符串中的大写字母
要计算字符串中的大写字母:
-
使用
for
循环遍历字符串。 -
使用
str.isupper()
方法检查每个字符是否为大写。 - 如果满足条件,则将计数变量递增 1。
my_str = 'FQLjiyik123'
uppercase_count = 0
for char in my_str:
if char.isupper():
uppercase_count += 1
print(uppercase_count) # 👉️ 3
我们使用 for 循环遍历字符串。
如果当前字符是大写字母,我们将存储在 uppercase_count 变量中的值增加 1。
+=
运算符是 uppercase_count = uppercase_count + 1
的简写。
以下代码示例实现了相同的结果。
my_str = 'FQLjiyik123'
uppercase_count = 0
for char in my_str:
if char.isupper():
uppercase_count = uppercase_count + 1
print(uppercase_count) # 👉️ 3
相关文章
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 日期时间。