私はこのようなアンダースコアで区切られた複数の単語の文字列を持っているをご覧ください。特定のインデックスのワード
このインデックスでは、アンダースコアの間に単語全体を入れたいと思っています。文字列のためにそう
[12]私はをスライス文字列を使用して「この」
私はこのようなアンダースコアで区切られた複数の単語の文字列を持っているをご覧ください。特定のインデックスのワード
このインデックスでは、アンダースコアの間に単語全体を入れたいと思っています。文字列のためにそう
[12]私はをスライス文字列を使用して「この」
非常にシンプルなアプローチはしている[1]私は戻って取得したい単語「文字列」と文字列のために戻って取得したいと思います:位置
split()
_
に基づいて各部分に基づいて、2つの部分に
サンプルコード:
>>> my_string = 'this_is_my_sample_string'
# ^index 14
>>> pos = 14
>>> my_string[:pos].split('_')[-1] + my_string[pos:].split('_')[0]
'sample'
@Downvoter:今後の回答を改善できるように、投票の理由を述べてください:) –
これは動作shuld:
string = 'this_is_my_string'
words = string.split('_')
idx = 0
indexes = {}
for word in words:
for i in range(len(word)):
idx += 1
indexes[idx] = word
print(indexes[1]) # this
print(indexes[12]) #string
次のコード作品。インデックスと文字列変数を変更し、新しい文字列に適応させることができます。また、新しい関数をコードで定義して一般化することもできます。正規表現の魔法の
string = 'this_is_my_string'
sp = string.split('_')
index = 12
total_len = 0
for word in sp:
total_len += (len(word) + 1) #The '+1' accounts for the underscore
if index < total_len:
result = word
break
print result
少し仕事をしていません:
import re
def wordAtIndex(text, pos):
p = re.compile(r'(_|$)')
beg = 0
for m in p.finditer(text):
#(end, sym) = (m.start(), m.group())
#print (end, sym)
end = m.start()
if pos < end: # 'pos' is within current split piece
break
beg = end+1 # advance to next split piece
if pos == beg-1: # handle case where 'pos' is index of split character
return ""
else:
return text[beg:end]
text = 'this_is_my_string'
for i in range(0, len(text)+1):
print ("Text["+str(i)+"]: ", wordAtIndex(text, i))
それは「_」文字でまたはエンドの文字列で入力文字列を分割して、反復的に指定された位置を比較し、実際の分割位置でのインデックス。
[Split stringをPythonのリストに分割]の可能な複製(http://stackoverflow.com/questions/743806/split-string-into-a-list-in-python) – aluriak
@aluriak私は思わないこれはあなたがリンクしたものと重複しています。これはちょうど分割する以上のものです。 – Lafexlos
これを実現する関数を書くことができます。しかし、私はあなたがインデックスを使用してこれを達成できるとは思わない。 – arulmr