python 字符串连接

python中字符串怎么连接呢?不知道的小伙伴来看看小编今天的分享吧!

python中字符串连接有七种方法。

方法一:用“+”号连接

用 “+”连接字符串是最基本的方式,代码如下。

>>> text1 = "Hello"

>>> text2 = "World"

>>> text1 + text2

'HelloWorld'

方法二:用“,”连接成 tuple (元组)类型

Python 中用“,”连接字符串,最终会变成 tuple 类型,代码如下:

>>> text1 = "Hello"

>>> text2 = "World"

>>> text1 , text2

('Hello','World')

>>> type((text1, text2))

<type 'tuple'>

>>>

方法三:用%s 占位符连接

%s 占位符连接功能强大,借鉴了C语言中 printf 函数的功能,这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:

>>> text1 = "Hello"

>>> text2 = "World"

>>> "%s%s"%(text1,text2)

'HelloWorld'

方法四:空格自动连接

>>> "Hello" "Nasus"

'HelloNasus'

值得注意的是,不能直接用参数代替具体的字符串,否则报错,代码如下:

>>> text1="Hello"

>>> text2="World"

>>> text1 text2

File "<stdin>", line 1

text1 text2

^

SyntaxError: invalid syntax

方法五:用“*” 连接

这种连接方式就是相当于 copy 字符串,代码如下:

>>> text1="nasus "

>>> text1*4

'nasus nasus nasus nasus '

>>>

方法六:join 连接

利用字符串的函数 join。这个函数接受一个列表或元组,然后用字符串依次连接列表中每一个元素:

>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']

>>> "".join(list1)

'Python'

>>>

>>> tuple1 = ('P', 'y', 't', 'h', 'o', 'n')

>>> "".join(tuple1)

'Python'

每个字符之间加 “|”

>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']

>>> "|".join(list1)

'P|y|t|h|o|n'

方法七:多行字符串拼接 ()

Python 遇到未闭合的小括号,自动将多行拼接为一行,相比三个引号和换行符,这种方式不会把换行符、前导空格当作字符。

>>> text = ('666'

'555'

'444'

'333')

>>> print(text)

666555444333

>>> print (type(text))

<class 'str'>

以上就是小编今天的分享了,希望可以帮助到大家。

标签:python 字符串连接

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
  • python爬虫能干什么
    python爬虫能干什么
    08-05
  • Python指的是什么语言
    Python指的是什么语言
    08-05
  • python主要做什么
    python主要做什么
    08-05
  • python extend
    python extend
    08-05
  • python object
    python object
    08-05
  • python可以用来做什么
    python可以用来做什么
    08-05
  • python是干什么用的
    python是干什么用的
    08-05
  • python是一种什么语言
    python是一种什么语言
    08-05
  • python函数大全及使用
    python函数大全及使用
    08-05
  • python index函数
    python index函数
    08-05