码迷,mamicode.com
首页 > 其他好文 > 详细

Pytyon字符串拼接的各种方式

时间:2019-09-03 16:16:13      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:div   import   str   注意   不能   for   form   format   多行   

#
#Pytyon字符串拼接的各种方式
#

#1、 %
str1="hello"
str2="world"
str="%s %s"%(str1,str2)
print(str)

#2、 + 
str1="hello"
str2="world"
str=str1+str2
print(str)

#3、 f-string Python 3.6中引入了
str1="hello"
str2="world"
str=f"{str1} {str2}"
print(str)

#4、 format
str1="hello"
str2="world"
str="{} {}".format(str1,str2)
print(str)

#5、 join
arr=["hello","world"]
str=" ".join(arr)
print(str)

#6、 * 字符串copy
str1="hello world! "
str=str1*3
print(str)


#7、 \ 多行拼接
str="hello ""world""!"
print(str)

#8、()  多行拼接
str=(
"hello"
" "
"world"
"!")
print(str)

#9、 template  注意str=temp.safe_substitute(a,b)这种方式是不可行的
from string import Template
a="hello"
b="world"
temp = Template("${str1} ${str2}!") 
str=temp.safe_substitute(str1=a,str2=b)
print(str) 

#10、 , 只能用于print,赋值等操作会生成元组
str1="hello"
str2="world"
print(str1,str2)

#11、 直接拼接  不能用变量,没有什么用
str=‘hello‘   ‘ world‘
print(str)
str=‘hello‘‘world‘
print(str)

  

Pytyon字符串拼接的各种方式

标签:div   import   str   注意   不能   for   form   format   多行   

原文地址:https://www.cnblogs.com/comprehension/p/11453485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!