首页 > 技术文章 > 字符串连接的5种方法

-simon 2016-09-20 09:41 原文

1. 加号

第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用 “+” 来连接两个字符串;

>>> print("hello "+"world")

hello world

2. 逗号

第二种比较特殊,使用逗号连接两个字符串,如果两个字符串用“逗号”隔开,那么这两个字符串将被连接,但是,字符串之间会多出一个空格;

>>> print('hello','world')

hello world

3. 直接连接

第三种也是 ,python 独有的,只要把两个字符串放在一起,中间有空白或者没有空白,两个字符串将自动连接为一个字符串;

>>> print('hello''world')

helloworld

或者

>>> print('hello'   'world')

helloworld

4. 格式化

第四种功能比较强大,借鉴了C语言中 printf 函数的功能,如果你有C语言基础,看下文档就知道了。这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:

>>> print('%s %s' % ('hello','world'))

hello world

5. join

就属于技巧了,利用字符串的函数 join 。这个函数接受一个列表,然后用字符串依次连接列表中每一个元素:

>>> str_list = ['hello','world']

>>> a = ''

>>> print(a.join(str_list))

helloworld

 

推荐阅读