0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python] 先頭/末尾の文字・空白を除去する方法

Last updated at Posted at 2021-03-11

概要

1: 先頭の文字を除去
2: 末尾の文字を除去
3: 空白を除去

※ 文字列の除去に関して使用する機会があったので、備忘録として記載
( 正規表現やスライスを使いこなせるようになると、もっと表現の幅が広がりそうなので少しづつ学んでいきたい。)

検証環境

OS:18.04.5 LTS
Python:3.6.9

方法

1: 先頭の文字を除去

lstrip()

型)文字列.lstrip()

# lstrip()を使用
word = "リトルグリーメン"

word = repr(word.lstrip(""))
print(word)

# 結果
'トルグリーメン'

2: 末尾の文字を除去

rstrip()

  • rstrip(right strip)は、文字列の右側から探索し、一番初めに該当した文字を除去する。

    型)文字列.rstrip()
# rstrip()を使用
word = "リトルグリーメン"

word = repr(word.rstrip(""))
print(word)

# 結果
'リトルグリーメ'

スライス

  • 負の値を指定してあげることで、末尾から指定した数値分除去できる。

    型)変数名[:-数値]
# スライスを使用
word = "リトルグリーメン"

word = repr(word[:-2])

# 結果
'リトルグリー'

3: 空白を除去

strip()

  • 文字列内に空白が入っていた場合、除去する。
# strip()を使用
word = " リトルグリーメン "

word = repr(word.strip())
print(word)

# 結果
'リトルグリーメン'
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?