Python ASCII字符数

时间:2015-10-24 01:47:36

标签: python ascii

我必须用Python编写一个程序,提示用户输入一个文本,然后用嵌套循环将该文本与ASCII字符串(所有ASCII字符)进行比较。

ascii_string= """!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""

user_text=input("Enter a text to analyze: ")

for character in (user_text):
    total_count= len(user_text)
    for user_text in (ascii_string):
        ascii_count=len(user_text)

print("Total number of characters: ", total_count)
print("Total number of ASCII characters: ", ascii_count)
print("Total number of non-ASCII characters: ", total_count-ascii_count)

2 个答案:

答案 0 :(得分:0)

是的,您确实使用了不合适的算法。对于输入字符串中的每个字符,您将保存整个输入字符串的长度,然后查看ASCII字符串中的每个字符并保存整个输入字符串的长度。试。

相反,将&#34;的所有布尔值加起来是在ASCII字符串&#34;通过将生成器传递给sum(),这将添加所有这些布尔值(True1False0):

ascii_string = set("""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""")

user_text = input("Enter a text to analyze: ")

total_count = len(user_text)
ascii_count = sum(c in ascii_string for c in user_text)

print("Total number of characters:", total_count)
print("Total number of ASCII characters:", ascii_count)
print("Total number of non-ASCII characters:", total_count-ascii_count)

答案 1 :(得分:0)

更好、更简单、更快捷的方法:


>>> s = "asdmlfjkéàç&-è'("
>>> ascii_count = len(s.encode("ascii", "ignore"))
>>> ascii_count
12