68

特定の文字の前の文字列の最後の部分を印刷しようとしています。

文字列 .split() メソッドを使用するか、文字列のスライスを使用するか、または他の何かを使用するかはよくわかりません。

これは機能しないコードですが、ロジックを示していると思います:

x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'

末尾の数値はサイズが異なるため、文字列の末尾からの正確な数を設定できないことに注意してください。

4

2 に答える 2

126

を探していますがstr.rsplit()、制限があります:

print x.rsplit('-', 1)[0]

.rsplit()入力文字列の末尾から分割文字列を検索し、2 番目の引数は、分割する回数を 1 回に制限します。

もう 1 つのオプションは、str.rpartition()一度だけ分割される を使用することです。

print x.rpartition('-')[0]

一度だけ分割する場合str.rpartition()も、より高速な方法です。複数回分割する必要がある場合は、 のみを使用できますstr.rsplit()

デモ:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

と同じstr.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
于 2013-04-06T13:47:57.423 に答える
5

分割パーティションの違いは分割であり、区切り記号なしのリストを返し、文字列で区切り記号を取得した場所で分割されます。

x = 'http://test.com/lalala-134-431'

a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"

パーティションは最初の区切り文字のみで文字列を分割し、リストに3つの値のみを返します

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"

最後の値が必要な場合はrpartitionを使用できますが、同じように機能しますが、文字列の末尾から区切り文字を見つけます

x = 'http://test.com/lalala-134-431'
a,b,c = x.rpartition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
于 2018-02-18T14:24:41.477 に答える