2017-08-09 82 views
0

的元素后,有没有办法将字符串转换“12345678aaaa12345678bbbbbbbb”在python“12345678-AAAA-1234-5678-BBBBBBBB”插入“ - ”字符串长度可变

我不知道该怎么做,因为我需要在可变长度的元素之后插入“ - ”之后的第8个元素,然后是第4个元素,等等。

+7

插入破折号的标准是什么?你有没有尝试过自己? –

回答

3

该函数在一个串中的现在的位置插入一个字符:

def insert(char,position,string): 
    return string[:position] + char + string[position:] 
1

Python字符串不能被突变。我们可以做的是根据您的意愿创建另一个字符串,并在其间插入连字符。

考虑字符串s =“12345678aaaa12345678bbbbbbbb” 给予s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb 你可以给连字符,你想通过调整:值。

有关添加连字符的更多方法,请参阅此问题主题以了解如何插入hypForhen。 Add string in a certain position in Python

+1

@NickA根据评论意见编辑了答案。 –

0

最简单的解决方案:

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阵列实现你想要的。

0

你可以按照这个过程:

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 
0

这不正是创造你想要的字符串,但无论如何张贴。

它找到数字变为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'

0

如果你想做到这一点的一个时间,你可以这样。 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) 
相关问题