【Python 训练营】N_13 遍历字符串

简介: 【Python 训练营】N_13 遍历字符串

题目

将字符串生成迭代器,逐个访问字符串中每个字符,并大写合并输出。

分析

字符串转换迭代器,for循环遍历字符串。

答案

# 方法一
s1 = 'Python'
l = []
for i in iter(s1): # 使用iter()函数生成迭代器
    l.append(i.upper())
print(''.join(l))

# 方法二
s1 = 'Python'
l = []
for i,char in enumerate(s1): # 使用enumerate()函数将字符串转换为索引序列
    l.append(char.upper())
print(''.join(l))

# 方法三
s1 = 'Python'
l = []
for i in range(len(s1)): # 通过range()生成数字列表
    l.append(s1[i].upper())
print(''.join(l))
相关文章
|
10月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
521 100
|
10月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
656 99
|
10月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
10月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
10月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
10月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
11月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
524 0
|
11月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
11月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
502 92

推荐镜像

更多