Inserting python in the middle of a line

I am new to python, have a book and am playing, so please be kind. I mainly play ASCII art

What I am trying to do is hide some art in some text. So tell me that I have a line that will print "word", what I want to do is write a function that helps me insert a character in the middle of that word, no matter how long that word is, it always puts my art character in the middle of the word. Therefore my conclusion will be 'word'. So far I've started:

def dashinsert(str):
    return str[:2] + '-' + str[2:]

      

I know this is not where close where it should be and I am just a beginner, but any direction for looking is appreciated, I am not sure if I am doing part of that right either

My goal is to learn from this and then insert random characters into words at different positions to make art in the text. those. i type a paragraph and art will insert itself as a function. Right now I'm just trying to get this insert part down

+3


source to share


3 answers


Use double slashes to separate integers



def dashinsert(str):
    midPoint = len(str)//2
    return str[:midPoint] + '-' + str[midPoint:]

      

+4


source


def insert_string(org_string, string, pos=None):
    # default position middle of org_string
    if pos is None:
        pos = len(org_string) / 2
    return org_string[:pos] + string + org_string[pos:]


if __name__ == "__main__":
    new_string = insert_string("world", "-")
    print new_string

      

Output



wo-rd

      

+2


source


You're in a good start! I'm a little rusty on my Python, but you can try adding a position parameter to change where inside the string to insert a dash (right now it's hardcoded as position 2:

def dashinsert(str, position):
    length = len(str)
    if (position > length or position < 0):
         return str
    return str[:position] + '-' + str[position:]

      

Or maybe you want to change the type of character you insert:

def characterinsert(str, position, insertion):
    length = len(str)
    if (position > length or position < 0):
         return str
    return str[:position] + insertion + str[position:]

      

Or maybe you want to randomize where you insert the symbol:

import random

def dashinsert(str, insertion):
    length = len(str)
    position = random.randint(0,length)
    return str[:position] + insertion + str[position:]

      

Then you can work in more advanced ways using ** kwargs and * args to change the parameters you pass to your function. Here's a good tutorial to get you started on these two concepts.

-1


source







All Articles