Skip to content

Instantly share code, notes, and snippets.

@takatakamanbou
Created October 22, 2020 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatakamanbou/0d8d0bdbe32d49300c1a267fd8d3704a to your computer and use it in GitHub Desktop.
Save takatakamanbou/0d8d0bdbe32d49300c1a267fd8d3704a to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# AProg2020 ex05 Notebook その3\n",
"\n",
"AProgのページ https://www-tlab.math.ryukoku.ac.jp/wiki/?AProg/2020"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"----\n",
"## 文字列型を使いこなす(pp.167-181の一部)\n",
"\n",
"上記の教科書の範囲から,「文字列の置換と削除」,「split()メソッドとjoin()メソッド」,「文字列で利用できるメソッド」について取り上げます.\n",
"\n",
"自分で教科書やその他の資料を参照しながらいろいろ考えて試行錯誤することが大事なところです.何が起こっているのかよく考えながら実行しましょう.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 文字列の置換と削除 & split()メソッドとjoin()メソッド\n",
"pp.167-171 を**読んで理解しながら**,以下を実行してみよう."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"orig_str = \"いっぱい\"\n",
"orig_str.replace(\"い\", \"お\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"-1\">(よだんだよん)\n",
"https://docs.python.jp/3/library/stdtypes.html#str.replace\n",
" によると,キーワード引数使って置換回数を指定できます....\n",
"</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"str_num = \"1,000,000\"\n",
"num = int(str_num.replace(\",\", \"\"))\n",
"num"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 練習\n",
"以下のセルに追記して, `(笑)` を `ww` にしましょう"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"str_ww = \"それはそれは(笑)...たいへんでしたね(笑)...\"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"どっちにしてもにくたらしいですな"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"str_speeds = \"38 42 20 40 39\" # 戦車のスピード(km/h)\n",
"str_armor = \"80 50 17 50 51\" # 戦車の装甲厚(mm)\n",
"speeds = str_speeds.split(\" \") # 速度をスペースで分割\n",
"armors = str_armor.split(\" \") # 装甲厚をスペースで分割\n",
"markers = [\"o\", \"v\", \"^\", \"<\", \">\"]\n",
"\n",
"for idx in range(len(speeds)): # リストの長さ分ループ\n",
" x = int(speeds[idx]) # 文字列を数値に変換\n",
" y = int(armors[idx])\n",
" plt.scatter(x, y, marker=markers[idx]) # 散布図を描く\n",
"\n",
"\n",
"#IV号戦車(o) LT-38(v) 八九式中戦車(^) III号突撃砲(<) M3中戦車(>)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"str_speeds = \"38 42 20 40 39\" # 空白で区切られた数値\n",
"speeds = str_speeds.split() \n",
"csep_speeds = \",\".join(speeds)\n",
"print(csep_speeds)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"str_speeds2 = \" 38 42 20 40 39 \" # 余分な空白が入った文字列\n",
"print(str_speeds2.replace(\" \", \",\")) # このように replace すると結果は..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"speeds2 = str_speeds2.split() # split してから join. それぞれのメソッドは何をしてる?\n",
"csep_speeds2 = \",\".join(speeds2)\n",
"print(csep_speeds2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 練習\n",
"以下の `str_ww2` の文は空白で区切られています.これを `(笑)...` で区切ったものにしてください.\n",
"```\n",
"それはそれは(笑)...たいへんでしたね(笑)...おつかれさまです\n",
"```\n",
"とする,ということです. split メソッドと join メソッドを使いましょう."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"str_ww2 = \"それはそれは たいへんでしたね おつかれさまです\"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 文字列で利用できるメソッド\n",
"pp.174-176を参考にしながら,いろいろやってみよう."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### その1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S = \"げほげほ...GEHOGOHOGEFU...GEHOGEFUN\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"この文字列の先頭から `\"HOGE\"` という文字列を探し,最初に見つけたものの位置を返すコードを書きましょう."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"# このセルにコードを書く\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"同じ文字列の先頭から `\"HOGE\"` という文字列を探し,2番目に見つけたものの位置を返すコードを書きましょう.\n",
"ここでは単純に,開始インデックスとして上記の戻り値より大きい数を指定すればよいです."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"# このセルにコードを書く\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### 練習\n",
"以下に二つセルを追加して,`S` の先頭から`\"hoge\"` および `\"ほげ\"` という文字列を探し,最初に見つけたものの位置を返すコードを書いてください.実行してどんな結果になるか確認してください."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### その2\n",
"以下の文字列 `S` は,`\"\\n\"`(改行文字)や`\"\\t\"`(タブ)を含んでいます(pp.172,173)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S = \"Hoge hoge \\n ほげ\\tHOGE\\n\"\n",
"print(\"#####\")\n",
"print(S)\n",
"print(\"#####\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"このような文字列に対して `split` メソッドを引数なしで適用すると,スペースだけでなく改行文字やタブも区切りとして文字列を分割します."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"T = S.split()\n",
"T"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(len(T)):\n",
" print(i, T[i])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"-1\">(よだんだよん) **正規表現**というものを利用する `re` モジュールを利用すると,文字列メソッドだけではできないようなもっと複雑な検索や置換等の処理ができます.\n",
"- Wikipedia 「正規表現」 https://ja.wikipedia.org/wiki/%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE\n",
"- re モジュール https://docs.python.jp/3/library/re.html\n",
"</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### その3\n",
"文字列に対して次のように `[ ]` を使うと,指定の位置の文字を取り出すことができます."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S = \"abcdefghijklmnopqrstuvwxyz\"\n",
"S[10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"スライスで部分列を指定することもできます."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S[10:15]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"スライスのステップ数を指定することもできます(詳しくはp.186)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S[10:15:2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"だからこうすると逆順の文字列が得られます."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"S[::-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"だからこうすると回文かどうか判定できます.\n",
"変数 `bun` の文字列を適当に変えていろいろ試してみてください."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bun = \"tomato\"\n",
"#bun = \"トマト\"\n",
"#bun = \"トメイトゥ\"\n",
"#bun = \"きつめのあなたににたなあのめつき\" # http://d.hatena.ne.jp/Quaibun/ より\n",
"#bun = \"ねつきわるいのいるわきつね\" # takataka作...文になってない\n",
"if bun == bun[::-1]:\n",
" print(\"回文です\")\n",
"else:\n",
" print(\"回文ではありません\") "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"これだと,`bun` とその逆順文字列の各文字を全部比較することになります.\n",
"本当はそれぞれの半分だけを比較すればok..."
]
}
],
"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.8.5"
},
"toc": {
"base_numbering": 1,
"nav_menu": {
"height": "146px",
"width": "258px"
},
"number_sections": false,
"sideBar": true,
"skip_h1_title": true,
"title_cell": "目次",
"title_sidebar": "Contents",
"toc_cell": true,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment