Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert spaces at certain locations in a string (Python 2.7)?

I've found many related questions, and a couple that have at least helped me get this far. My goal is to have a function that receives a string and an arbitrary number of integers. I want the function to return that string with spaces inserted at the points given in the arguments. I will use this function with many different strings that will have varying numbers of inserts and insert locations.

This is an example of what I'd like to produce:

Input a string like 'ATGCATGCATGCATGC' and indexes (e.g. 4, 7). The output should be 'ATGCA TGC ATGCATGC'.

This is the function that has given me the closest results so far:

def breakRNA(seqRNA, *breakPoint):
    n = 0
    for i in seqRNA:
        n += 1
        for i in breakPoint:
            if i == n:
                seqRNA = seqRNA[n:] + ' ' + seqRNA[:n]
    return seqRNA     

The return string, however, is transposed out of order. Example:

>>> test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
>>> test
>>> 'TTTTTGGGGGGGGCCCCCCCCCC AAAAA AAAAAAAA AAAAAAAAAAAAAA'

I am a day-1 beginner so any advice is appreciated. Thank you.

like image 308
boloyao Avatar asked May 09 '26 02:05

boloyao


1 Answers

String are indexed like list in Python. For example consider the following:

test_string = "azertyuiop"
print test_string[0] #will return 'a'
print test_string[0:2] #will return 'az'

So getting back to your problem:

def insert_space(string, integer):
    return string[0:integer] + ' ' + string[integer:]
like image 113
Ketouem Avatar answered May 10 '26 15:05

Ketouem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!