Home > Software design >  I want to duplicate a random letter of a string 1 time. How can I do?
I want to duplicate a random letter of a string 1 time. How can I do?

Time:07-20

This is my string:

keyword = "qatarworldcup"

I mean my string should be qqatarworldcup, qatarworldcupp or qatarrworlddcup

CodePudding user response:

This should be pretty easy to do if you break it up into parts.

  1. Select a random letter from the word.
import random
letter_index = random.randint(0, len(keyword)-1)
  1. Split the word into two parts at the letter you picked.
before, after = keyword[:letter_index], keyword[letter_index:]
  1. Join the two parts, adding an extra instance of the selected letter
result = before   keyword[letter_index]   after

If your strings are big enough, or you're doing this multiple times, you could see a speedup from reducing the number of string concatenations, because that's an O(N) operation on account of the immutability of strings. Since the selected letter already exists in the word, you can split it such that the selected letter is the last character of before and the first character of after. Then, you only need a single concatenationThanks to @Mechanic Pig for your comment:

before, after = keyword[:letter_index 1], keyword[letter_index:]
result = before   after

CodePudding user response:

from random import randint
keyword = "qatarwordcup"
idx = randint(0, len(keyword) - 1)
keyword = keyword[:idx]   keyword[idx]   keyword[idx:]

CodePudding user response:

I'd do it like this

import random

#Find random position in string
r = random.randint(0, len(keyword) - 1)
#Create new string with added character at random position
newStr = keyword[:r]   keyword[r]   keyword[r:]
  • Related