技術共有

第 6 章 文字列オブジェクトとスライス操作

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

目次

第 6 章 文字列オブジェクトとスライス操作

6.1 文字列オブジェクト

6.2 文字でよく使用されるメソッド

6.3 スライス操作

第 6 章 文字列オブジェクトとスライス操作

6.1 文字列オブジェクト

文字列: 複数の文字で構成される文字列

文字:肉眼で見える記号

バイト: 肉眼では見えません

Python が文字列を定義する方法:

一重引用符 二重引用符 三重引用符 str()

6.2 文字でよく使用されるメソッド

 >>> dir(s)
 ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Capitalize ------- 文字列の最初の文字を大文字にします

 >>> s
 'this is a string'
 >>> s.capitalize()
 'This is a string'

center(width, fillchar=' ') ------- 指定された長さに従って文字列を中央揃えにし、中央に揃えます

rjust --------- 右揃え

ljust ------ 左揃え

 >>> help(s.center)
 Help on built-in function center:
 ​
 center(width, fillchar=' ', /) method of builtins.str instance
     Return a centered string of length width.
 ​
     Padding is done using the specified fill character (default is a space).
 ​
 >>> s.center(40)
 '            this is a string            '
 >>> s.center(40,"*")
 '************this is a string************'
 >>> s.rjust(40)
 '                        this is a string'
 >>> s.ljust(40)
 'this is a string                        '
 >>> s.ljust(40,"*")
 'this is a string************************'
 >>> s.rjust(40,"*")
 '************************this is a string'

count ------------- 文字列内に文字が出現する回数をカウントします。

 >>> s
 'this is a string'
 >>> s.count("s")
 3
 >>> s.count("is")
 2

endwith ------- 文字列が XXX で終わるかどうかを判断します。

startswith ------- 文字列が XXX で始まるかどうかを判断します

 >>> s.endswith("g")
 True
 >>> s.endswith("ing")
 True
 >>> s.endswith("f")
 False
 >>> s.startswith("t")
 True
 >>> s.startswith("f")
 False

インデックス ------ 検索された文字または文字列が文字列内で最初に出現する位置。 存在しない場合は、例外 (エラー レポート) がスローされます。

rindex ------- 右から左に検索します。検索対象の文字または文字列が文字列内で最初に出現する位置 (文字列内で左から右に検索する文字または文字列が最後に出現する位置に相当します)。 )、存在しない場合は例外をスローします(エラーを報告します)。

 >>> s
 'this is a string'
 >>> s.index("s")
 3
 >>> s.index("is")
 2
 >>> s.index("f")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 ValueError: substring not found
 >>> s.index(" ")
 4
 >>> s.rindex("s")
 10
 >>> s.rindex("f")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 ValueError: substring not found

find ------- 文字列内で検索対象の文字または文字列が最初に出現する位置。存在しない場合は、-1 が返されます。

rfind----- 右から左に、文字列内で最初に出現する文字または文字列の位置 (文字列内で左から右に最後に出現する文字または文字列の位置と同等) を検索します。存在しない場合は -1 を返します

 >>> s
 'this is a string'
 >>> s.find("s")
 3
 >>> s.find("f")
 -1
 >>> s.rfind("f")
 -1
 >>> s.rfind("s")
 10

encode ----- python3で文字列をバイトに変換するメソッド、バイトを文字列に変換するdecode()メソッド(バイト単位のメソッド)

 >>> s
 'this is a string'
 >>> s.encode()
 b'this is a string'
 >>> d = s.encode()
 >>> d
 b'this is a string'
 >>> type(d)
 <class 'bytes'>
 >>> d
 b'this is a string'
 >>> d.decode()
 'this is a string'
 >>> ss = d.decode()
 >>> ss
 'this is a string'
 >>> type(ss)
 <class 'str'>

format ------ 文字列のフォーマット、文字列の連結

isupper ------ 文字列がすべて大文字であるかどうかを判断します。

is lower ----- ------ 文字列がすべて小文字であるかどうかを判断します

>>> s.isupper()
False
>>> s.islower()
False

istitle ----- タイトルかどうかを判断します

>>> s.istitle()
False
>>> ss = "This Is A Dog"
>>> ss.istitle()
True

isspace ----- スペースであるかどうかを判断するためには一般的には使用されません。

>>> sss = "       "
>>> sss.isspace()
True
>>> ss
'This Is A Dog'
>>> ss.isspace()
False

isdigital ------ 数値かどうかを判断します

>>> sss = "123234344"
>>> sss.isdigit()
True
>>> ss
'This Is A Dog'
>>> ss.isdigit()
False
>>> sss = "1233443gggg"
>>> sss.isdigit()
False

isalnum ------ 文字と数字 (英数字) であるかどうかを決定します

>>> help(s.isalnum)
Help on built-in function isalnum:

isalnum() method of builtins.str instance
    Return True if the string is an alpha-numeric string, False otherwise.

    A string is alpha-numeric if all characters in the string are alpha-numeric and
    there is at least one character in the string.

>>> sss
'1233443gggg'
>>> sss.isalnum()
True
>>> ss
'This Is A Dog'
>>> ss.isalnum()
False

isalpha ------ それが文字であるかどうかを決定します

title ----- 文字列をタイトル形式に変換します

>>> s
'This is a string'
>>> s.istitle()
False
>>> s.title()
'This Is A String'
>>> sss = s.title()
>>> sss
'This Is A String'
>>> sss.istitle()
True

upper ------- 文字列を大文字に変換します

lower ------- 文字列を小文字に変換します

>>> s
'This is a string'
>>> s.lower()
'this is a string'
>>> s.upper()
'THIS IS A STRING'

split ----- 指定された記号に従って文字列を分割し、戻り値はリストになります

>>> s
'This is a string'
>>> s.split(" ")
['This', 'is', 'a', 'string']
>>> l = s.split(" ")
>>> l
['This', 'is', 'a', 'string']
>>> type(l)
<class 'list'>
>>> l = s.split("s")
>>> l
['Thi', ' i', ' a ', 'tring']

join ------ 指定された形式に従って反復可能なオブジェクトを文字列に連結します

>>> ls = ["A","B","c","d"]
>>> type(ls)
<class 'list'>
>>> ss = " ".join(ls)
>>> ss
'A B c d'
>>> type(ss)
<class 'str'>
>>> ss = "*".join(ls)
>>> ss
'A*B*c*d'

ストリップ ------- 両側のスペースを削除します

rstrip------ 右側のスペースをクリアします

lstrip -------- 左側のスペースをクリアします

>>> ss = "                              hhhhhhh                                  "
>>> ss
'                              hhhhhhh                                  '
>>> ss.strip()
'hhhhhhh'
>>> ss.strip()
'hhhhhhh'
>>> ss
'                              hhhhhhh                                  '
>>> ss.rstrip()
'                              hhhhhhh'
>>> ss.lstrip()
'hhhhhhh                                  '

replace ("元の文字", "新しい文字") ------- 対応する文字を置換します

>>> s
'This is a string'
>>> s.replace("s","t")
'Thit it a ttring'

6.3 スライス操作

スライス: 反復可能なオブジェクト (コンテナー) を分離するために使用されます。

文法規則:

object[start_index:end_index:step]

start_index ------- 開始インデックス (開始位置)

end_index ------ 終了インデックス (終了位置)、end_index の値は含まれません

step ---- ステップの長さ。正の数値または負の数値を指定できます。正の数値 (左から右)、負の数値 (右から左)、デフォルト値は 1 です。

object[:]  ----- 切割的是一个完整的对象
object[start_index:]  ------ 从start_index开始切割到最后的位置,步长为1
object[:end_index] ------ 从最开始的位置切割到end_index处,但是不包含end_index
object[start_index:end_index] ------- 从start_index开始切割到end_index处,但是不包含end_index,步长为1
object[start_index:end_index:step] ------------ 从start_index开始切割到end_index处,但是不包含end_index,步长为step  

前閉じと後ろ開きの間隔

= [0,1,2,3,4,5,6,7,8,9]

1. 単一の値を切り取る

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[0]
0
>>> ls[-4]
6

2. 完全なオブジェクトを切り取ります

>>> ls[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[::-1]  #-1 表示从右往左切割 所以是倒序
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

3. start_index と end_index はどちらも正の数です

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[1:6]
[1, 2, 3, 4, 5]
>>> ls[1:6:-1]  # start_index=1 end_index = 6表示的是从1切割到6的位置,但是不包含6处的值,从左往右切割,step=-1 表示从右往左   
[]
>>> ls[6:1]
[]
>>> ls[6:1:-1]
[6, 5, 4, 3, 2]
>>> ls[:6]
[0, 1, 2, 3, 4, 5]
>>> ls[:6:-1]
[9, 8, 7]
>>> ls[6:]
[6, 7, 8, 9]
>>> ls[6::-1]
[6, 5, 4, 3, 2, 1, 0]
>>>

4. start_index と end_index は両方とも負の数です

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[-1:-6]
[]
>>> ls[-1:-6:-1]
[9, 8, 7, 6, 5]
>>> ls[-6:-1]
[4, 5, 6, 7, 8]
>>> ls[:-6]
[0, 1, 2, 3]
>>> ls[:-6:-1]
[9, 8, 7, 6, 5]
>>> ls[-6:]
[4, 5, 6, 7, 8, 9]
>>> ls[-6::-1]
[4, 3, 2, 1, 0]

5. Start_index と end_index は正と負で結合されます

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[1:-6]
[1, 2, 3]
>>> ls[1:-6:-1]
[]
>>> ls[-1:6]
[]
>>> ls[-1:6:-1]
[9, 8, 7]

6. 連続スライス

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[:8][2:5][-1:]
[4]
ls[:8] ----- [0,1,2,3,4,5,6,7]
ls[:8][2:5]   -----   [2,3,4]
ls[:8][2:5][-1:] ----- [4]

7. スライスの 3 つのパラメータは式にすることもできます

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[2+1:3*2:7%3]
[3, 4, 5]
>>> ls[3:6:1]
[3, 4, 5]
>>> ls[2:6:2]
[2, 4]

8. スライスすると他のオブジェクトも切断できます

>>> (1,2,3,4,5,6,7,8,9)[:3]
(1, 2, 3)
>>> "ABCDEFGHIJK"[::2]
'ACEGIK'
>>> for i in range(1,100)[2::3][-10:]:
...     print(i)
...
72
75
78
81
84
87
90
93
96
99

面接の質問:

1. スライスを使用してデータを切り取るときに添字の範囲を超えた場合、エラーが報告されますか?

範囲を超えた場合、エラーは報告されません。矛盾している場合は、完全なオブジェクトが返されます。

2.Pythonでリストを逆出力するにはどうすればよいですか?

ループリバース

[::-1]

リストを逆にする()