python字符串连接
1. python 字符串连接
1.不推荐使用
a = ['a','b','c','d']
content = ''
for i in a:
content = content + i
2.
a = ['a','b','c','d']
content = ''
content = ''.join(a)
3.
a = ['a','b','c','d']
content = ''
content = '%s%s%s%s' % tuple(a)
print content
2. 为什么Python 可以使用 + 把两个字符串连接成一个字符串
这是python中的字符串的功能。其实当使用加号运算符的时候会调用这个类的__add__()函数,这个函数是每个类都有的,对于自定义的类,不重写这个方法,+这个运算符就没作用。你也可以重写这个运算符来得到不同的功能。以下是示例代码。class vector: def __init__(self,x=0,y=0): self.x=x self.y=y def __add__(self, other):#重载__add__方法,可以实现+法运算 if isinstance(other,vector): return vector(self.x+other.x,self.y+other.y) else: raise TypeError('other parameter must be a vector') va=vector(3,5)vb=vector(4,6)vc=va+vbprint('vc.x=%s;vc.y=%s'%(vc.x,vc.y))
3. 在python中怎么连接变量和字符串
python中变量和字符串的连接
字符串中加含变量,一定要内外包围相同版。
如下输出权:
table='abc'
str1='select * from '+table+''
str2="select * from "+table+""
str3='select * from "'+table+'"'
str4="select * from '"+table+"'"
print 'str1 is :',str1
print 'str2 is :',str2
print 'str3 is :',str3
print 'str4 is :',str4
输出结果:
[python] view plain
str1 is : select * from abc
str2 is : select * from abc
str3 is : select * from "abc"
str4 is : select * from 'abc'
4. python 字符串 拼接问题
f=open('A.txt')
d=f.readlines()
f.close()
foriinrange(0,len(d),2):
print"%s:%s"%(d[i].strip(),d[i+1].strip())
结果:
192.168.1.1:8080
192.168.1.4:8081
192.168.5.1:80
5. Python中字符串有哪些连接方法
1. 使用 '+' 连接
例如 s = s+ 'hello world!'
这种方式最慢
2. 使用 ' +='
例如 s += 'hello wold'
这种方式与第一种作用相同,但是效版率权高一点
3.使用 ".join(list)"
这种方式效率最高
使用时可以先用一个list缓存字符串,然后使用join方法,得到最终结果
4.python的字符串格式化操作符 %
例如 s = '%s New %s !'%('Happy','Year')
这种方式会让代码的可读性更好,也不用对非字符串调用str方法
6. python字符串怎么和整数连接
1、在python中完成字符串复和数字的拼接制,可以使用内置函数str()。
7. Python字符串拼接的几种方法
Python字符串拼接的几种方法(python3.5):
1、str1+str2
使用+号进行字符串拼接:'wbz'+'ctt'='wbzctt'
2、str1,str2
这种方式有点特殊,如果两个字符串用逗号隔开,那么两个字符串就会被拼接,严格讲不
叫拼接:'wbz','ctt'=('wbz’,'ctt')
3、str1str2
这种拼接方式是Python独有的,只要将两个字符串放在一起,这两个字符串就会自动拼接
成新的字符串,不管这两个字符串中间是否存在空格:'wbz''ctt'='wbzctt'
'wbz''ctt'='wbzctt'
4、%连接字符串
这种方式相对于其他的拼接方式来说就有些强大了,因为它借鉴了C语言中printf()函数
的功能。这种方式用符号'%'连接一个字符串和一组变量,字符串中的特殊标记会被自动用
右边变量组中的变量替换:'%s%s'%('wbz','ctt')='wbzctt'
5、字符串列表连接str.join(list)
这个函数join接受一个列表,并用字符串连接列表中的每一个元素:
data=['wbz','ctt','Python']
str='**##'
str.join(data)='wbz@@@ctt@@@Python'
6、字符串乘法
这种方法也是可以进行字符串拼接的,但是这种方式是不经常使用的:
str='Python'
str*2='PythonPython'
8. python中字符串拼接
if__name__=='__main__':
result=''
data=['num1','num2','num3','num4']
foriinrange(len(data)):
result+='OR'+'''+data[i]+'''
print(result)
9. python用字符串拼接一条语句,然后怎么执行
defcutbody(*args):
printargs[0][args[1]:args[2]]
cutbody('11111',2,3)
改成这样可能会简便一点吧,希望能帮到你~
10. python字符串连接的几种方式总结
1、相袭加
website = 'python' + 'tab' + '.com'
2、%
'my name is %s,now %d years old' % ('liming',27)
3、{}.format
'myname is {0},now {1} years old'.format('liming','27')