Python字符串练习

  1. 输入一行字符,统计其中有多少个单词,每两个单词之间以空格隔开。如输入: This is a c++ program. 输出:There are 5 words in the line. 【考核知识点:字符串操作】 代码:
s=input("请输入一行句子:")
list = s.split(' ')
print("There are %d words in the line." %len(list))

运行结果:

另外考虑到有时候手抖多敲了空格,于是又想了一种方法:

count = 0
s=input("输入字符:")
for i in range(len(s)):
	if i+1 > len(s);
		count+=1
	else:
		if s[i] == ' ' and s[i+1] != ' ':
			count+=1
  1. 给出一个字符串,在程序中赋初值为一个句子,例如"he threw three free throws",自编函数完成下面的功能: 1)求出字符列表中字符的个数(对于例句,输出为26); 2)计算句子中各字符出现的频数(通过字典存储); ---学完字典再实现
  1. 将统计的信息存储到文件《统计.txt》中; --- 学完文件操作再实现 代码:
def function(s):
	print("字符串中字符的个数为: %d" %len(s))
	dict = {}
	for i in s:
		if i in dict:
			dict[i] += 1
		else:
			dict[i] = 1
	f = open("统计.txt","w")
	for i in dict:
		f.write(i+":"+str(dict[i])+"\t")
	f.close()
string = input("请输入字符串:")
function(string)

执行结果:

可以看到生成了“统计.txt”文件。打开查看是否正确写入内容,

  1. (2017-好未来-笔试编程题)--练习
  • 题目描述: 输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”

  • 输入描述: 每个测试输入包含2个字符串

  • 输出描述: 输出删除后的字符串

  • 示例1:

输入
    They are students.
    aeiou
输出
    Thy r stdnts.

代码:

str1 = input("请输入第一个字符串:")
str2 = input("请输入第二个字符串:")
str3 = ''
for i in str2:
	if i not in str3:
		str3+=i
for i in str3:
	str1=str1.replace(i,'')
print(str1)

运行结果:

  1. (2017-网易-笔试编程题)-字符串练习

小易喜欢的单词具有以下特性: 1.单词每个字母都是大写字母 2.单词没有连续相等的字母 列可能不连续。 例如: 小易不喜欢"ABBA",因为这里有两个连续的'B' 小易喜欢"A","ABA"和"ABCBA"这些单词 给你一个单词,你要回答小易是否会喜欢这个单词。

  • 输入描述: 输入为一个字符串,都由大写字母组成,长度小于100

  • 输出描述: 如果小易喜欢输出"Likes",不喜欢输出"Dislikes"

示例1 :

输入
    AAA
输出
    Dislikes

代码:

s = input("请输入字符串:")
for i in range(len(s)):
	if s[i] < 'A' or s[i] >'Z':
		print("Dislike")
		break
	else:
		if i < len(s)-1 and  s[i] == s[i+1]:
			print("Dislike")
			break
else:
	print("Likes")

执行结果: