面试题--关于字符串

1.  反转一个整数的数字

考点:反转可以使用切片,切片可以反转字符串和list

 1 #反转一个整数的数字
 2 '''首先是一个数字
 3 1. 正数:123-->321
 4 2. 0-->0
 5 3. 负数:-123-->-321
 6 反转:切片可以反转字符串,但是现在类型是数字,需要把数字转为字符串
 7 '''
 8 
 9 def reverse_number(n):
10     if not isinstance(n,int):   #如果不是整数,则返回一个None
11         return None
12     if n>0:   #判断是正数,转换为字符串
13         s=str(n)
14         s=s[::-1]
15         result = int(s)   #将字符串类型转换为整数
16     
17     elif n==0:
18         return 0
19     else:
20         s=abs(n)
21         s=str(s)
22         s=s[::-1]
23         result = -1 * int(s)
24     return result
25 #打印输入-123,反转为多少
26 print(reverse_number(-123))

2. 统计一句话中单词的数量

 考点:

1.字符串的切割   

2.字符串的拼接 (字符串无法修改,只能生成一个新的去拼接 )  

3.字符串的遍历

4.如何判断一个值是不是字母

5.判断列表的长度

 1 #统计一句话中单词的数量
 2 #'i am a good boy!you too!'
 3 a = 'i am a good boy!you too!'
 4 #遍历一遍,把非字母的内容替换为空格
 5 new_a=''
 6 for i in a:
 7     if (i>='a' and i<='z') or (i>='A' and i<='Z'):
 8         new_a+=i
 9     else:
10         new_a+=' '
11 print(new_a) 
12 num_a = new_a.split()
13 print(num_a)
14 print(len(num_a))
#统计一句话中单词的数量
#封装成一个函数
#'i am a good boy!you too!'
def word_num(a):
    #遍历一遍,把非字母的内容替换为空格
    #严谨一些,先判断传入的a是不是一个字符串
    if not isinstance(a,str):
        return None
    else:
        new_a=''
        for i in a:
            if (i>='a' and i<='z') or (i>='A' and i<='Z'):
                new_a+=i
            else:
                new_a+=' '
        num_a = new_a.split()
        return(len(num_a))

print(word_num(123))
原文地址:https://www.cnblogs.com/cudy/p/13476979.html