まぬねこの足跡。。。

備忘録+たのしさ+ひっそりと

Python - str.strip([chars]):文頭、文末 除去

概要

str.strip([chars])

str:除去される文字列
chars:除去する文字列。省略時、空白。

  • 文頭、文末 除去
  • 組込み型 文字列メソッド

実行結果

print(" abcde "  .strip())
print("     abcde   ".strip())
print("####abcde####".strip('#'))
print("#-#-abcde#-#-"  .strip('#-'))

表示イメージ

abcde
abcde
abcde
abcde

Python - str.startswith(prefix[, start[, end]]):文頭が指定文字列か

概要

str.startswith(prefix[, start[, end]])

str:検索される文字列
prefix:検索文字列
start,end:スライスと同一

  • 文頭が指定文字列か
  • 組込み型 文字列メソッド

実行結果

print("1234567123456712345671234567".startswith("123"))
print("1234567123456712345671234567".startswith("567"))
print("1234567123456712345671234567".startswith("456",3))
print("1234567123456712345671234567".startswith("712",6,20))
print("1234567123456712345671234567".startswith("345",6,10))

表示イメージ

True
False
True
True
False

Python - str.splitlines(keepends=False):改行で分割+リスト化

概要

str.splitlines(keepends=False)

str:改行を含んだ文字列
keepends:Trueでリストに改行を含む

  • 改行で分割+リスト化
  • 組込み型 文字列メソッド

実行結果

print('11 1\n\n22 22\r33\r\n'.splitlines())
print('11 1\n\n22 22\r33\r\n'.splitlines(keepends=True))
ward='''11111
22

33 333
4
5 5 5
'''
print(ward.splitlines())
print(ward.splitlines(keepends=True))

表示イメージ

['11 1', '', '22 22', '33']
['11 1\n', '\n', '22 22\r', '33\r\n']
['11111', '22', '', '33 333', '4', '5 5 5']
['11111\n', '22\n', '\n', '33 333\n', '4\n', '5 5 5\n']

Python - str.split(sep=None, maxsplit=- 1):前から、文字列分割

概要

str.split(sep=None, maxsplit=- 1)

str:区切り文字を含んだ文字列
sep:区切り文字。省略時、空白
maxsplit:最大区切り数

  • 前から、文字列分割
  • 組込み型 文字列メソッド

実行結果

print("123,45,678,9".split(","))
print("123,45,678,9".split(",",2))
print("123,45,678,9".split(",",maxsplit=2))
print("123,45,678,9".split(" "))

表示イメージ

['123', '45', '678', '9']
['123', '45', '678,9']
['123', '45', '678,9']
['123,45,678,9']

Python - str.rstrip([chars]):文末 除去

概要

str.rstrip([chars])

str:除去される文字列
chars:除去する文字列。省略時、空白。

  • 文末 除去
  • 組込み型 文字列メソッド

実行結果

print(" abcde "  .rstrip())
print("     abcde   ".rstrip())
print("####abcde####".rstrip('#'))
print("#-#-abcde#-#-"  .rstrip('#-'))

表示イメージ

 abcde
     abcde
####abcde
#-#-abcde