python怎么获取已输入的文本框 (python中怎么截取字符串中的字符)

如何在Python中获取字符串中的唯一字符

要在 Python 中获取字符串中的唯一字符,有两种不同的方案:

  • 删除重复项后获取字符串中的唯一字符。
  • 检索字符串中只出现一次的字符。

利用集合从字符串中获取唯一字符

Python 集合是一个不包含重复元素的无序序列。我们利用这一特性,从字符串中获取唯一字符。

>>> str1 = "Hello World"
>>> set(str1)
{'l', 'W', 'o', 'r', ' ', 'e', 'd', 'H'}

我们得到了一个集合,集合不能包含重复的元素,字母“l”、“o”只出现一次。正是我们想要的结果。可以使用字符串连接方法来生成字符串。

>>> str1 = "Hello World"
>>> "".join(set(str1))
'lWor edH'

获取唯一字符并保持其顺序

使用集合获取为义字符无法保持字符的原有顺序。如果想保留字符的顺序,我们可以创建一个新的空字符串,使用 for 循环,遍历原始字符串的每个字符,如果该字符不在新字符串中,则将字符连接到新字符串。

str1 = "Hello World"
str2 = ""
for char in str1:
    if char not in str2:
        str2 += char
print(str2)

我们也可以使用列表存储字符,最后连接列表元素,得到新字符串。

str1 = "Hello World"
list1 = []
for char in str1:
    if char not in list1:
        list1.append(char)
print("".join(list1))

查找不重复的字符

使用 collections 库的 Counter 方法,将字符串转换为字典并计数。

>>> from collections import Counter
>>> str1 = "Hello World"
>>> Counter(str1)
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})

利用列表推导式获取不重复字符

>>>  [key for key in Counter(str1).keys() if Counter(str1)[key] == 1]
['H', 'e', ' ', 'W', 'r', 'd']

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!