04python 字符串2练习题(统计不同字符个数-判断回文数字-字符串内置函数应用)

字符串应用练习题

1、 练习:练习17:题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

import string 
s = raw_input('请输入一个字符串:\n') 
letters = 0 
space = 0 
digit = 0 
others = 0 
for c in s: 
    if c.isalpha(): 
        letters += 1 
    elif c.isspace(): 
        space += 1 
    elif c.isdigit(): 
        digit += 1 
    else: 
        others += 1 
print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))

2、 练习30题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = int(input("请输入一个数字:\n"))
x = str(a)
flag = True
for i in range(len(x)/2):
if x[i] != x[-i - 1]:
    flag = False
    break
if flag:
    print ("%d 是一个回文数!" % a)
else:
   print ("%d 不是一个回文数!" % a)

字符串内置函数练习

#字符串大小写转换
str1 = " how are you?"
print("第一个字母大写:",str1.capitalize())
print("每个单词的第一个字母大写:",str1.title())
print("所有字母都大写:",str1.upper())
print("所有字母都小写:",str1.lower())

判断是字符串

#字符串判断

str1 = "How  Are You?"
print(str1)
print("判断所有字符都是数字或字母:",str1.isalnum())
print("判断所有字符都是字母:",str1.isalpha())
print("判断所有字符都是数字:",str1.isdigit())
print("判断所有字符都是大写:",str1.isupper())
print("判断所有字符都是小写:",str1.islower())
print("判断所有单词都是 首字母大写:",str1.istitle())
print("判断所有字符都是空格:",str1.isspace())

输出

How  Are You?
判断所有字符都是数字或字母: False
判断所有字符都是字母: False
判断所有字符都是数字: False
判断所有字符都是大写: False
判断所有字符都是小写: False
判断所有单词都是 首字母大写: True
判断所有字符都是空格: False

你可能感兴趣的:(04python 字符串2练习题(统计不同字符个数-判断回文数字-字符串内置函数应用))