{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 字符串遍历"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"字符串的遍历是指用循环的方法依次获取字符串中的每个字符"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for c in string: # 变量c依次取值为字符串中的字符\n",
" 语句块"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"string为字符串 \n",
"循环次数为字符串中字符个数 \n",
"变量c依次被赋值为字符串中的字符"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"输入一个字符串,逐行输出其中的字符。(竖向输出一个字符串)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" nanning\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"n\n",
"a\n",
"n\n",
"n\n",
"i\n",
"n\n",
"g\n"
]
}
],
"source": [
"my_string = input() # 输入一个字符串\n",
"for c in my_string: # 遍历,c依次取值为字符串中的字符\n",
" print(c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 实例6.8 分类统计字符个数 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"输入一个字符串,统计字符串里英文字母、数字和其他字符的个数。"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" jkgkdgh230那个经理\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"字母7个, 数字3个, 其他字符4个\n"
]
}
],
"source": [
"import string # 导入string库,使用库中字符会串常量\n",
" \n",
"my_string = input() # 输入一个字符串\n",
"letter, digit, other = 0, 0, 0 # 用于计数的3个变量均设初值为0\n",
"for c in my_string: # 遍历,c依次取值为字符串中的字符\n",
" if c in string.ascii_letters: # 若c在字母常量中存在,则c是字母\n",
" letter = letter + 1 # 字母计数加1个\n",
" elif c in string.digits: # 若c在数字常量中存在,则c是数字\n",
" digit = digit + 1 # 数字计数加1个\n",
" else:\n",
" other = other + 1 # 否则其他字符计数加1个\n",
"print(f\"字母{letter}个, 数字{digit}个, 其他字符{other}个\")\n",
"# 123 The operators in and not in test for membership 456.\n",
"# 字母39个, 数字6个, 其他字符11个"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"my_string = input() # 输入一个字符串\n",
"letter, digit, other = 0, 0, 0 # 用于计数的3个变量均设初值为0\n",
"for c in my_string: # 遍历,c依次取值为字符串中的字符\n",
" if c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' : # 若c在字母常量中存在,则c是字母\n",
" letter = letter + 1 # 字母计数加1个\n",
" elif c in '0123456789': # 若c在数字常量中存在,则c是数字\n",
" digit = digit + 1 # 数字计数加1个\n",
" else:\n",
" other = other + 1 # 否则其他字符计数加1个\n",
"print(f\"字母{letter}个, 数字{digit}个, 其他字符{other}个\")\n",
"# 123 The operators in and not in test for membership 456.\n",
"# 字母39个, 数字6个, 其他字符11个"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}