📌  相关文章
📜  Python|检查字符串是否包含所有相同字符的方法

📅  最后修改于: 2022-05-13 01:55:06.462000             🧑  作者: Mango

Python|检查字符串是否包含所有相同字符的方法

给定一个字符串列表,编写一个Python程序来检查每个字符串的所有字符是否相同。下面给出了一些检查方法。

方法#1:使用朴素方法[低效]

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using Naive Method:
flag = True
for i in ini_list:
    for j in range(0, len(i)-1):
        if i[j]!= i[j + 1]:
            print ("String {} don't have all characters same".format(i))
            flag = False
            break
    if flag == True:
        print ("String {} don't have all characters same".format(i))
         
输出:
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa don't have all characters same
String aaaaaaabaa don't have all characters same


方法#2:使用字符串比较

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using String comparison
for i in ini_list:
    if i == len(i)*i[0]:
        print ("String {} have all characters same".format(i))
    else:
        print ("String {} don't have all characters same".format(i))
         
输出:
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same


方法#3:使用计数比较

# Python code to demonstrate 
# to check whether string contains
# all characters same or not
  
# Initialising string list
ini_list = ["aaaaaaaaaaa", "aaaaaaabaa"]
  
# Printing initial string
print ("Initial Strings list", ini_list)
  
# Using String comparison
for i in ini_list:
    if i.count(i[0]) == len(i):
        print ("String {} have all characters same".format(i))
    else:
        print ("String {} don't have all characters same".format(i))
         
输出:
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same