master
/ 5.2.4 字符串的遍历.ipynb

5.2.4 字符串的遍历.ipynb @masterview markup · raw · history · blame

Notebook

字符串遍历

字符串的遍历是指用循环的方法依次获取字符串中的每个字符

In [ ]:
for c in string:        # 变量c依次取值为字符串中的字符
    语句块

string为字符串
循环次数为字符串中字符个数
变量c依次被赋值为字符串中的字符

输入一个字符串,逐行输出其中的字符。(竖向输出一个字符串)

In [1]:
my_string = input()  # 输入一个字符串
for c in my_string:  # 遍历,c依次取值为字符串中的字符
    print(c)
n
a
n
n
i
n
g

实例6.8 分类统计字符个数

输入一个字符串,统计字符串里英文字母、数字和其他字符的个数。

In [2]:
import string                      # 导入string库,使用库中字符会串常量
 
my_string = input()                # 输入一个字符串
letter, digit, other = 0, 0, 0     # 用于计数的3个变量均设初值为0
for c in my_string:                # 遍历,c依次取值为字符串中的字符
    if c in string.ascii_letters:  # 若c在字母常量中存在,则c是字母
        letter = letter + 1        # 字母计数加1个
    elif c in string.digits:       # 若c在数字常量中存在,则c是数字
        digit = digit + 1          # 数字计数加1个
    else:
        other = other + 1          # 否则其他字符计数加1个
print(f"字母{letter}个, 数字{digit}个, 其他字符{other}个")
# 123 The operators in and not in test for membership 456.
# 字母39个, 数字6个, 其他字符11个
字母7个, 数字3个, 其他字符4个
In [2]:
my_string = input()                # 输入一个字符串
letter, digit, other = 0, 0, 0     # 用于计数的3个变量均设初值为0
for c in my_string:                # 遍历,c依次取值为字符串中的字符
    if c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' :  # 若c在字母常量中存在,则c是字母
        letter = letter + 1        # 字母计数加1个
    elif c in '0123456789':       # 若c在数字常量中存在,则c是数字
        digit = digit + 1          # 数字计数加1个
    else:
        other = other + 1          # 否则其他字符计数加1个
print(f"字母{letter}个, 数字{digit}个, 其他字符{other}个")
# 123 The operators in and not in test for membership 456.
# 字母39个, 数字6个, 其他字符11个
In [ ]: