この記事はPythonの文字列操作方法(コード例)をまとめたものです。参考になると思います。困っている方は参考にしてください。お役に立てれば幸いです。
文字列 (文字列):
文字列の定義と作成:
定義: 文字列は、基本的なテキスト メッセージを保存および表現するために使用される、順序付けられた文字のコレクションです。
注: 文字列内の単一引用符も二重引用符も、特殊文字の意味を取り消すことはできません。引用符内で
1 2 | var1='Hello World!'
print (var1)
|
ログイン後にコピー
を使用したい場合は、対応する操作:
1, "*"出力文字を繰り返します。 String
1 | print ('Hello World'*2)
|
ログイン後にコピー
2,"[]","[:]" インデックスを介して文字列内の文字を取得します。これは、リスト
のスライス操作と同じです。
1 | print ('Hello World'[2: ])
|
ログイン後にコピー
3. "in" メンバー演算子は、文字列に指定された文字が含まれる場合に True を返します
1 | print ('el' in 'Hello World')
|
ログイン後にコピー
4,"%"Format string
1 2 | print ('alex is a good teacher')
print ('%s is a good teacher' %'alex')
|
ログイン後にコピー
5," 文字列のスプライシング
1 2 3 4 | a ='123'
b='abc'
c=a+b
print (c)
|
ログイン後にコピー
注: " " は非効率です。join を使用してください
1 2 | c=''.join([a,b])
print (c)
|
ログイン後にコピー
文字列の一般的なメソッド:
文字列、インターセプト、コピー、接続、比較、検索、分割
#capitalize: 最初の文字は大文字、他の文字は小文字です
1 2 3 | s='asf sgs SD dfs ASdf'
print (s.capitalize())
>>Asf sgs sd dfs asdf
|
ログイン後にコピー
# lower() 小文字に変換
#upper () 大文字に変換
#swapase() 大文字と小文字を入れ替え
1 2 3 4 5 6 7 8 9 | a='hello word'
print (a.upper())
b='HELLO WORD'
print (b.lower())
c='hello WORD'
print (c.swapcase())
>>HELLO WORD
>>hello word
>>HELLO word
|
ログイン後にコピー
#s.strip(): 文字列の両側の指定された文字を削除します。デフォルトはempty
1 2 3 4 | s=' hello '
b=s.strip()
print (b)
>>hello
|
ログイン後にコピー
#s.lstrip(): 文字列の左側の指定された文字を削除します。
#s.rstrip(): 文字列の左側の指定された文字を削除します。文字列、
1 2 3 4 5 6 7 | s=' hello '
b=s.ltrip()
c=s.rtrip()
print (b)
print (c)
>>hello
>> hello
|
ログイン後にコピー
#文字列をコピー
1 2 3 4 | a='hello'
b=a*2
print (b)
>>hellohello
|
ログイン後にコピー
#2 つの文字列を接続します str.join
1 2 3 4 5 | a='hello'
b='123'
a.join(b)
print (a.join(b))
>>1hello2hello3
|
ログイン後にコピー
#文字列 str.index を検索します。 str.find にも同じ機能があります。
違いは、インデックスが見つからず、エラーが報告されることです。 find は、見つからない場合は「-1」を返します。両方が見つかった場合は、最初に見つかった文字列の位置を返します。
#
1 2 3 4 5 | a='hello word'
print (a.index('w'))
print (a.find('a'))
>>6
>>-1
|
ログイン後にコピー
# 指定された文字列が「入っている」か「入っていない」かを判断します
1 2 3 4 5 | a='hello word'
print ('hello' in a)
print ('hello' not in a)
>>True
>>False
|
ログイン後にコピー
#文字列の長さを表示 len
1 2 3 | a='hello word'
print (len (a))
>>10
|
ログイン後にコピー
#srt.centen 文字列を中央位置に置き、両方の長さと文字を指定しますポジションの両側
1 2 3 | a='chen zheng'
print (a.center(20, "*" ))
>>*****chen zheng*****
|
ログイン後にコピー
rreerree
以上がPythonでの文字列操作方法まとめ(コード例)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。