python

当前位置:中华考试网 >> python >> python编程基础 >> 文章内容

如何在Python字符串中快速拼接

来源:中华考试网  [2020年10月23日]  【

  在Python中,字符串是一种常用的数据类型。对字符串的定义及表达方式有了了解后,接下来的学习,将为大家讲解如何使用Python来实现字符串的拼接。

  1.加号拼接

1

2

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">s = "Hello" +  " " + "world" + " I"

print(s)

  输出结果:

  2. ( ) 拼接

1

2

3

4

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">liststr = ['Hello','World','I']

strlist = ''.join(liststr)

print('转换后的数据类型是:',type(strlist))

print('转换后的数据是:',strlist)

  输出结果:

  3. 操作符拼接

1

2

3

4

5

6

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">s = "{} {}".format('Hello','World')

print('输出结果是:',s)

s1 = "{0} {1}".format('Hello','world')

print('s1的结果是 {}'.format(s1))

s2 = "{a} {b}".format(a='Hello',b='world')

print('s2的结果是 {}'.format(s2))

  输出结果:

  4.(%)操作符进行拼接

1

2

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">s = "%s %s "%('Hello','world')

print(s)

  输出结果:

  5.通过()进行拼接

1

2

3

4

5

6

7

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">s=(

    'hello' + '\n'

    ''

    'World' + '\n'

    '!'

)

print(s)

  输出结果:

  6.F-string拼接 (该方法适用于版本)

1

2

3

"line-height: 1.75em;">"font-family: 微软雅黑, "Microsoft YaHei";">s1="Hello"

s2="World"

print(f'{s1} {s2}')

  在版本不兼容报错:

  以上就是在Python中关于字符串拼接的几种简单方式,其他方式欢迎大家评论补充,一起携手向Python进阶迈进。

责编:fushihao
  • 会计考试
  • 建筑工程
  • 职业资格
  • 医药考试
  • 外语考试
  • 学历考试