Reputation: 79
I am new to python, have a book and playing around so please be kind. Mainly I have been playing with ASCII art
What I am trying to do is hide some art into some text. So say I have a string print out "word", what I want to do is write a function that helps me insert a character into the middle of that word regardless of how long the word is, it always places my art character into the middle of the word. So my output would be 'wo-rd'. What I have started with so far is:
def dashinsert(str):
return str[:2] + '-' + str[2:]
I know that this is no where close on where it needs to be, and I am only a beginner, but any direction to look is appreciated, I am not sure I am doing some of this right either
My goal is to learn from this and then insert random characters into words at various positions to make art in text. ie I type a paragraph and the art will insert itself as a function. Right now I am just trying to get this insert portion down
Upvotes: 5
Views: 14504
Reputation: 7500
You're off to a good start! I'm a little rusty on my Python, but you can try adding in a position parameter to vary where inside the string to insert the 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 vary what 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 character:
import random
def dashinsert(str, insertion):
length = len(str)
position = random.randint(0,length)
return str[:position] + insertion + str[position:]
Then you can work on more advanced ways, using ** kwargs and *args to vary the parameters you pass into your function. Here's a good tutorial to start learning about those two concepts.
Upvotes: 0
Reputation: 628
Use double slashes for integer divide
def dashinsert(str):
midPoint = len(str)//2
return str[:midPoint] + '-' + str[midPoint:]
Upvotes: 6
Reputation: 512
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
Upvotes: 2