LoginSignup
0
0

More than 5 years have passed since last update.

文字列でも計算(演算)できるんだって

Last updated at Posted at 2019-04-18

前回:https://qiita.com/New_enpitsu_15/items/1813d05e4671ea99f6fc
次回:https://qiita.com/New_enpitsu_15/items/1b0f404b0ade21dbe2cd
目次:https://qiita.com/New_enpitsu_15/private/479c69897780cabd01f4

Pythonでは、文字列にも演算子を使うことができます。

概要

例えば、"+"で文字列同士を結合。

>>> "Apple" + "Pen"
'ApplePen'
>>> AP = "Apple" + "Pen"
>>> print(AP)
ApplePen
>>> PP = "Pen" + "Pineapple"
>>> print(PP)
PenPineapple

と、変数に代入した場合でも同じような処理を行えます。

>>> PPAP = AP + PP
>>> print(PPAP)
ApplePenPenPineapple
>>>

加えて、"*"で文字に数値をかけることで数値回数繰り返すことができます。

>>> "str" * 3
'strstrstr'
>>>

利用例

例えば、input()を使ってユーザー名を入力させたものを表示したり

user_name = input()#HBenpitsu
print("プレイヤーの名前を" + user_name + "で登録しました。")
#プレイヤーの名前をHBenpitsuで登録しました。
input()

いろーーーーーんなことができます。今のところ具体的な活用例は示せそうにありませんが、
これを活用すればCUI(黒い画面)でも比較的見栄えのいい画面が実現できます。

終わりに

今回 "+" と "*" だけ紹介しましたが、文字列の計算、文字列操作はさまざまなものがあります。
CUIにプリントするだけではなく、テキストファイルの編集、などなどいろいろなことに、文字列操作は使われます
詳しくは説明しませんが、調べてみるといいかもしれません。

様々な文字列操作がまとめられている記事です。: Python文字列操作マスター

余談
print("A","B")
#A B
print("A","B",sep="")
#AB
A = (1,2,1,3,7,6,4,5)
print(*A,sep=",")
#1,2,1,3,7,6,4,5
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0