Python字符串替换 [英] Python string replace

查看:258
本文介绍了Python字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

    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. 您不需要自己制作字母表, import string 并使用 string.ascii_uppercase ;和

  2. 您可以使用代替循环来处理您键中的字符。

  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, "")

更好的是, list 是可变的,因此您可以:

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))

这篇关于Python字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆