0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python 文字列の小技

Posted at

printの中で改行する

printの中で改行しようとすると

print内で改行
print("
line1
line2
line2
")

# SyntaxError: unterminated string literal

このようにエラーが出てしまう
改行したい場合は以下のようにする

print内で改行する
print("start")
print("""
line1
line2
line3
""")

#start

#line1
#line2
#line3

print("""の後に改行出力されるのでstartとline1の間に隙間がある
startのすぐ下にline1を出力する場合は\(バックスラッシュ)をつける

print内で改行する
print("start")
print("""\
line1
line2
line3
""")

#start
#line1
#line2
#line3

\(バックスラッシュ)をコード内に使うと改行を無視してつづけて書くことができる

バックスラッシュで改行を無視
value = "123\
456"
print(value)

#123456

クソ長変数やurlを扱うときに使えるかも(?)

文字列を置き換える

文字列のインデックスを指定して文字を置き換えることはできない

インデックスで置き換え
word = "hello"
word[2] = "y"
print(word)

# TypeError: 'str' object does not support item assignment

スライスを使って変数を宣言することで置き換えることができる

スライスを使って置き換える
word = "hello"
word = word[:2] + "y" + word[3:]
print(word)

# heylo

<文字列>.replace(<変換前文字>, <変換後文字>)でも置き換えることができるが指定したすべての文字を置き換えてしまう

string.replaceをつかう
word = "いっぱい"
word.replace("", "")
pirnt(word)

# おっぱお

文字列の中から文字列を探す

<元の文字列>.find(<探したい文字列 | 探したい文字>)で文字列を左から探索して最初に合致した探したい文字列のインデックスを取得できる

findを使う
word = "hello mike."
print(word.find("mi")

# 6

一番最初のインデックスは "0"

rfindは後ろから探索して取得する

rfindを使う
word = "hello"
# 左の"l"を取得
print(word.find("l")) # 2
# 右の"l"を取得
print(word.rfind("l")) # 3

スライスと組み合わせて応用すると最初の%と最後の%の間の文字を変更できる

findとスライス
word = "hello %mike% nice to meet you!"
new_word = word[:word.find("%") + 1] + "jordan" + word[word.rfind("%"):]
print(new_word)

# hello %jordan% nice to meet you!

f-stringsを使う

formatメソッドはf-stringsで代用できる
print(f"<文字列>{<変数>}<文字列>")のようにすることで文字列の中に変数を挿入できる
コードが読みやすくなるので積極的に使おう

f-strings
print("id: {id}, name: {name}".format(id = 123, name = "dopamine"))

# id: 123, name: dopamine

id = 123
name = "dopamine"
print(f"id: {id}, name: {name}")

#id: 123, name: dopamine

終わりに

調べものの途中でf-stringsを見つけることができたので満足です。
道中の収穫も馬鹿にできない・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?