的元素後,有沒有辦法將字符串轉換「12345678aaaa12345678bbbbbbbb」在python到「12345678-AAAA-1234-5678-BBBBBBBB」?插入「 - 」字符串長度可變
我不知道該怎麼做,因爲我需要在可變長度的元素之後插入「 - 」之後的第8個元素,然後是第4個元素,等等。
的元素後,有沒有辦法將字符串轉換「12345678aaaa12345678bbbbbbbb」在python到「12345678-AAAA-1234-5678-BBBBBBBB」?插入「 - 」字符串長度可變
我不知道該怎麼做,因爲我需要在可變長度的元素之後插入「 - 」之後的第8個元素,然後是第4個元素,等等。
該函數在一個串中的現在的位置插入一個字符:
def insert(char,position,string):
return string[:position] + char + string[position:]
Python字符串不能被突變。我們可以做的是根據您的意願創建另一個字符串,並在其間插入連字符。
考慮字符串s =「12345678aaaa12345678bbbbbbbb」 給予s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb
你可以給連字符,你想通過調整:
值。
有關添加連字符的更多方法,請參閱此問題主題以瞭解如何插入hypForhen。 Add string in a certain position in Python
@NickA根據評論意見編輯了答案。 –
最簡單的解決方案:
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
i = -1
for index in indexes:
i = i + index + 1
str = str[:i] + '-' + str[i:]
print str
打印:12345678-aaaa-1234-5678-bbbbbbbb
你可以自由地改變indexes
陣列實現你想要的。
你可以按照這個過程:
def insert_(str, idx):
strlist = list(str)
strlist.insert(idx, '-')
return ''.join(strlist)
str = '12345678aaaa12345678bbbbbbbb'
indexes = [8, 4, 4, 4]
resStr = ""
idx = 0
for val in indexes:
idx += val
resStr = insert_(str,idx)
str = resStr
idx += 1
print(str)
輸出:
12345678-aaaa-1234-5678-bbbbbbbb
這不正是創造你想要的字符串,但無論如何張貼。
它找到數字變爲alpha的所有索引,反之亦然。 然後它在這些索引處插入「 - 」。
a = "12345678aaaa12345678bbbbbbbb"
lst = list(a)
index = []
for ind,i in enumerate(list(a)[:-1]):
if (i.isdigit() and lst[ind+1].isalpha()) or (i.isalpha() and lst[ind+1].isdigit()):
index.append(ind)
for i in index[::-1]:
lst.insert(i+1,"-")
''.join(lst)
'12345678-AAAA-12345678-BBBBBBBB'
如果你想做到這一點的一個時間,你可以這樣。 str =「12345678aaaa12345678bbbbbbbb」
def insert(char,positions,string):
result = ""
for post in range(0, len(positions)):
print(positions[post])
if post == 0:
result += string[:positions[post]] + char
elif post == (len(positions) -1):
result += string[positions[post-1]:positions[post]] + char + string[positions[post]:]
else:
result += string[positions[post-1]:positions[post]] + char
print(result)
return result
insert("-", [8, 12, 16, 20], str)
插入破折號的標準是什麼?你有沒有嘗試過自己? –