如何用python拼接字符串,去空格

作者:暴躁小n | 创建时间: 2023-04-25
python拼接字符串有三种方法,每种方法的效率和使用的场景各不相同。python在处理字符串上有它自己的优势,简洁高效。...
如何用python拼接字符串,去空格

操作方法

直接用“+”进行拼接,优点是简洁,缺点是当拼接的字符串多的情况下,效率低下

采用join方法,将list中的元素拼接成字符串拼接

使用reduce函数进行字符串的 #!/usr/bin/env pythonfrom functools import reduceimport operatorlist1 = ['hello',' ','world']result = reduce(operator.add,list1,'')print result

python去掉空格方法 #!/usr/bin/env pythonstr1 = "a b d    e d f g"str1 =str1.replace(' ','')print(str1)

取字符串第一个字符 #!/usr/bin/env pythonstr1 = "a b d    e d f g"str1 =str1.replace(' ','')print(str1[0])

取字符串最后一个字符 #!/usr/bin/env pythonstr1 = "a b d    e d f g"str1 =str1.replace(' ','')print(str1[-1])

点击展开全文

更多推荐