华南俳烁实业有限公司

python

當前位置:中華考試網(wǎng) >> python >> python編程基礎(chǔ) >> 文章內(nèi)容

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

來源:中華考試網(wǎng)  [2020年10月23日]  【

  在Python中,字符串是一種常用的數(shù)據(jù)類型。對字符串的定義及表達方式有了了解后,接下來的學(xué)習(xí),將為大家講解如何使用Python來實現(xiàn)字符串的拼接。

  1.加號拼接

1

2

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

print(s)

  輸出結(jié)果:

  2. ( ) 拼接

1

2

3

4

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

strlist = ''.join(liststr)

print('轉(zhuǎn)換后的數(shù)據(jù)類型是:',type(strlist))

print('轉(zhuǎn)換后的數(shù)據(jù)是:',strlist)

  輸出結(jié)果:

  3. 操作符拼接

1

2

3

4

5

6

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

print('輸出結(jié)果是:',s)

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

print('s1的結(jié)果是 {}'.format(s1))

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

print('s2的結(jié)果是 {}'.format(s2))

  輸出結(jié)果:

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

1

2

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

print(s)

  輸出結(jié)果:

  5.通過()進行拼接

1

2

3

4

5

6

7

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

    'hello' + '\n'

    ''

    'World' + '\n'

    '!'

)

print(s)

  輸出結(jié)果:

  6.F-string拼接 (該方法適用于版本)

1

2

3

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

s2="World"

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

  在版本不兼容報錯:

  以上就是在Python中關(guān)于字符串拼接的幾種簡單方式,其他方式歡迎大家評論補充,一起攜手向Python進階邁進。

責(zé)編:fushihao
  • 會計考試
  • 建筑工程
  • 職業(yè)資格
  • 醫(yī)藥考試
  • 外語考試
  • 學(xué)歷考試
财经| 静乐县| 综艺| 新平| 高阳县| 增城市| 宜州市| 宁海县| 衡水市| 开化县| 辽宁省| 宜城市| 沙洋县| 永清县| 施甸县| 资中县| 维西| 墨玉县| 礼泉县| 绍兴市| 乐平市| 荣昌县| 伊宁市| 慈溪市| 确山县| 乐业县| 灵山县| 富锦市| 舟山市| 阜城县| 长宁县| 长白| 宜丰县| 鸡西市| 连州市| 奇台县| 定安县| 昌乐县| 天柱县| 彩票| 紫阳县|