Python中字符串的 join()函数简单用法

  • 函数名:join()
  • 作用:将可迭代对象中的字符串类型数据,提取出来,串联在一起,具体见实例
  • 调用方法:str.join(iterable)
  • 参数:
    iterable:可迭代的对象,如列表,字符串等

官方解释:
str.join(iterable)

Return a string which is the concatenation of the strings in iterable.

A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

大意翻译:

返回一个字符串,它是iterable中字符串的串联。如果iterable中有任何非字符串值,包括bytes对象,则会引发一个类型错误。元素之间的分隔符是提供此方法的字符串。

少废话,上例子:

"""
以列表为例,如列表中的元素全部为字符串类型
若想要将所有字符串提取出来,组成一个字符串
无需遍历循环,可简单使用join()函数
"""
lt = ["a", "b", "c"]

print("".join(lt))#abc
print(type("".join(lt)))#<class 'str'>

"""
字符串类型同样适用
"""
s = "  World"

print("Hello" + "".join(s))#Hello  World

"""
如果你用一个非空的字符串调用join()函数
那它不但会把那个迭代对象里的字符串提取到最后的输出里
还会将那个非空字符串也加到最后输出里
而且是每遍历一个元素,加一次
但是最后一个元素不会加
见例子!!!
"""

print("Hello".join(s))
#结果:' Hello HelloWHellooHellorHellolHellod'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值