test = ["hello", "world", "yoyo"] print("_".join(test))
结果:
hello_world_yoyo
如果不依赖 python 提供的 join 方法,还可以通过 for 循环,然后将字符串拼接,但是在用“+”连接字符串时,结果会生成新的对象,使用 join 时结果只是将原列表中的元素拼接起来,所以 join 效率比较高。 for 循环拼接如下:
test = ["hello", "world", "yoyo"] # 定义一个空字符串 j = '' # 通过 for 循环打印出列表中的数据 for i in test: j = j + "_" + i # 因为通过上面的字符串拼接,得到的数据是“_hello_world_yoyo”,前面会多一个下划线_,所以把这个下划线去掉 print(j.lstrip("_"))
3. 把字符串 s 中的每个空格替换成”%20”,输入:s = “We are happy.”,输出:“We%20are%20happy.”。
使用 replace 函数,替换字符换即可:
s = 'We are happy.' print(s.replace(' ', '%20')) 12
结果:
We%20are%20happy.
4. Python 如何打印 99 乘法表?
for 循环打印:
for i in range(1, 10): for j in range(1, i+1): print('{}x{}={}\t'.format(j, i, i*j), end='') print()
while 循环实现:
i = 1 while i <= 9: j = 1 while j <= i: print("%d*%d=%-2d"%(i,j,i*j),end = ' ') # %d: 整数的占位符,'-2'代表靠左对齐,两个占位符 j += 1 print() i += 1
5. 从下标 0 开始索引,找出单词 “welcome” 在字符串“Hello, welcome to my world.” 中出现的位置,找不到返回 -1。
deftest(): message = 'Hello, welcome to my world.' world = 'welcome' if world in message: return message.find(world) else: return-1
print(test())
结果: 7
6. 统计字符串“Hello, welcome to my world.” 中字母 w 出现的次数。
deftest(): message = 'Hello, welcome to my world.' # 计数 num = 0 # for 循环 message for i in
message: # 判断如果 ‘w’ 字符串在 message 中,则 num +1 if'w'in i: num += 1 return num
print(test())
# 结果 2
7. 输入一个字符串 str,输出第 m 个只出现过 n 次的字符,如在字符串 gbgkkdehh 中,找出第 2 个只出现 1 次的字符,输出结果:d
deftrim(s): flag = 0 if s[:1]==' ': s = s[1:] flag = 1 if s[-1:] == ' ': s = s[:-1] flag = 1 if flag==1: return trim(s) else: return s print(trim(' Hello world! '))
通过 while 循环实现:
deftrim(s): while(True): flag = 0 if s[:1]==' ': s = s[1:] flag = 1 if s[-1:] == ' ': s = s[:-1] flag = 1 if flag==0: break return s print(trim(' Hello world! '))
16. 将字符串 s = “ajldjlajfdljfddd”,去重并从小到大排序输出”adfjl”。
deftest(): s = 'ajldjlajfdljfddd' # 定义一个数组存放数据 str_list = [] # for循环s字符串中的数据,然后将数据加入数组中 for i in s: # 判断如果数组中已经存在这个字符串,则将字符串移除,加入新的字符串 if i in str_list: str_list.remove(i)
:param count: count为 1,则表示计算最大值,为 2 时,表示最小值 :return: """ # for 循环查询列表中的数据 for i in self.L1: if count == 1: # 循环判断当数组中的数据比初始值小,则将初始值替换 if i > self.num: self.num = i