python challenge 1、3:字符串处理

python challenge 1:字符串处理

图中给了三个字母的映射,都是把字母映射到ASSII码+2的字母上。

http://www.pythonchallenge.com/pc/def/map.html

>>> ns=""
>>> for c in s:
    if c.isalpha():
        if(c<='x'):
            ns+=chr(ord(c)+2)
        else:
            ns+=chr(ord(c)+2-26)
    else:
        ns+=c
       
>>> ns
"i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url."

1、python里面字符串是属于常量类型,因此不能像C一样s[i]='a'这样操作,只能在字符串后面连接新串

2、介绍几个关于字母的函数

s.isalnum() 所有字符都是数字或者字母
s.isalpha() 所有字符都是字母
s.isdigit() 所有字符都是数字
s.islower() 所有字符都是小写
s.isupper() 所有字符都是大写
s.istitle() 所有单词都是首字母大写,像标题
s.isspace() 所有字符都是空白字符、	、
、

3、ord与chr是字符yu十进制ASSIC码相互转换

>>> c="a"
>>> ord(c)
97
>>> chr(97)
'a'

另外,python可以直接使用类型名函数直接在整数与字符串之间相互转化

>>> c="32"
>>> int(c)
32
>>> str(32)
'32'

python字符串处理功能异常强大,下面继续介绍一些常用的字符串处理函数与方法

第3题:给定一个长字符串,要求找出本身是小写字母,前三个后三个都必须是大写字母,并且左右两侧的大写字母个数仅可以为3.

#s=''.join([c for c in s if c != '
'])
#s=''.join(s.split())
s.replace('
','')
ns=''
l=len(s)
for i in range(3,l):
    if s[i-3:i].isupper() and s[i+1:i+4].isupper() and s[i].islower():
        if i<=3:
            if not s[i+4].isupper():
                ns+=s[i]
        elif i>=l-4:
            if not s[i-4].isupper():
                ns+=s[i]
        elif s[i+4].islower() and s[i-4].islower():
            ns+=s[i]
print ns

首先把换行符给去掉。python字符串是固定的,因此只能读取原字符串内容,再重新生成一个新的串。

方法1:使用for语句加if生成一个列表,再join

方法2:split默认参数时把所有空字符,包括空格、制表、换行等去掉,再jion

方法3:字符串子代一个replace的方法

原文地址:https://www.cnblogs.com/iyjhabc/p/3268984.html