栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 假设有一段英文,其中有单独的字母I误写为i,请编写程序进行纠正。

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 假设有一段英文,其中有单独的字母I误写为i,请编写程序进行纠正。

输入一段英文,将其中单独字母的i修改为I,单词部分中的i不进行修改。

例:

输入:i will go with you

输出:I will go with you

输入:so do i

输出:so do I

输入:so i will go with you

输出:so I will go with you

 代码一(利用列表的特性):

st = input("请输入:")              # 输入字符串
result = []                        # 创建空列表
for i in range(len(st)):
    if st[i] != 'i':
        result.append(st[i])
    elif st[i] == 'i':
        if i == len(st)-1:
            if st[i-1] == ' ':     # 判断该字符是否为i并且是最后一位且为单字母
                result.append('I')
            else:
                result.append(st[i])
        else:
            if st[i-1] == ' ' and st[i+1] == ' ':        # 判断该点是否为单字母
                result.append('I')
            else:                    # 不为单字母便是单词直接添加到列表result里面
                result.append(st[i])

if result[0] == 'i' and result[1] == ' ':        # 判断第一个字母是否为单字母并且为i
    result[0] = 'I'

print(''.join(result))            # 将空格作为连字符并输出

代码二(利用字符串特性及其函数)

st = input("请输入:")
result = []
st1 = st.split()            # 将空格作为分隔符返回输入的字符串分割后的结果(转化为列表)
for i in range(len(st1)):
    if len(st1[i]) != 1:    # 判断每一个元素是否为单词(等于1就是单字母)
        result.append(st1[i])
    else:
        result.append(st1[i].replace('i', 'I'))    # 将单字母i替换成I添加到result里
print(' '.join(result))        # 以空格为间隔符输出列表result

所用到的函数有split()、join()、replace() 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号