0

I have this code:

    ALPHABET1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    key = "TES"
    ALPHABET2 = key + ALPHABET1
    count_result = ALPHABET2.count("T")
    if (count_result > 1):
    ALPHABET3 = ALPHABET1.replace("T","")
    ALPHABET2 = key + ALPHABET3         
    print(ALPHABET2)

I want to be able to put the keyword at the start of the alphabet string to create a new string without repeating the letters in the keyword. I'm having some problems doing this though. I need the keyword to work for all letters as it will be user input in my program. Any suggestions?

1
  • string is a "tuple" of values. You could make a set of letters, than convert back to string(draw back for simple implementation is that order it's changed). But I think a simple parser-loop for eache letter, in a list comprehension-it may be the right solution for you. If it sound strange, tell me and I expand this in an answer Commented Jan 24, 2014 at 19:42

2 Answers 2

1

Two things:

  1. You don't need to make the alphabet yourself, import string and use string.ascii_uppercase; and
  2. You can use a for loop to work through the characters in your key.

To illustrate the latter:

for c in key:
    alphabet = alphabet.replace(c, "")

Better yet, a list is mutable, so you can do:

alpha = [c for c in string.ascii_uppercase if c not in key]
alpha.extend(set(key))
Sign up to request clarification or add additional context in comments.

2 Comments

Neither of the approaches I outline needs to know the length of the key. A for loop works through however many characters there are.
yeah.. i figured it out just after posting :))
0

its easy and clean to do this with a regex

import re

ALPHABET1   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key         = "TES"
newalphabet = key.upper() + re.sub(r'%s'%'|'.join(key.upper()), '', ALPHABET1)

or with a list comprehension like @jonrsharpe suggested

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.