输入一段英文,将其中单独字母的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()