本文目录一览:
python字符串连接的几种方式总结
- 相加
website = 'python' + 'tab' + '.com'
- %
'my name is %s,now %d years old' % ('liming', 27)
.format
'myname is {0},now {1} years old'.format('liming', '27')
python字符串常用方法
- Python字符串拼接(包含字符串拼接数字)
- Python截取字符串(字符串切片)
- Python 的
len()
函数:获取字符串长度或字节数 - Python
split()
方法:分割字符串 - Python
join()
方法:合并字符串 - Python
count()
方法:统计字符串出现的次数 - Python
find()
方法:检测字符串中是否包含某子串 - Python
index()
方法:检测字符串中是否包含某子串 - Python字符串对齐方法(
ljust()
、rjust()
和center()
) - Python
startswith()
和endswith()
方法 - Python字符串大小写转换(3种)函数
- Python去除字符串中空格(删除指定字符)的3种方法
python 文本字符串接
Python中有很多字符串连接方式,今天在写代码,顺便总结一下:
- 最原始的字符串连接方式:
str1 + str2
- Python 新字符串连接语法:
str1, str2
- 奇怪的字符串方式:
str1 str2
%
连接字符串:'name:%s; sex: ' % ('tom', 'male')
- 字符串列表连接:
str.join(some_list)
- 直接用
+
来连接两个字符串:'Jim' + 'Green' = 'JimGreen'
- 两个字符串用“逗号”隔开,中间会多出一个空格:
'Jim', 'Green' = 'Jim Green'
- Python 独有的方式,两个字符串放在一起,自动连接为一个字符串:
'Jim''Green' = 'JimGreen' 'Jim' 'Green' = 'JimGreen'
- 使用
%
连接字符串和变量:'%s, %s' % ('Jim', 'Green') = 'Jim, Green'
- 使用
join
函数连接列表中的元素:var_list = ['tom', 'david', 'john'] a = '###' a.join(var_list) = 'tom###david###john'
- 字符串乘法:
a = 'abc' a * 3 = 'abcabcabc'
字符串拼接的多种方式
方法一:+
s1 = "hello"
s2 = "world"
s3 = s1 + s2
print(s3)
方法二:join
str.join(sequence)
示例:
s1 = "-"
s2 = ['hello', 'world']
s3 = s1.join(s2)
print(s3)
方法三:%
符号拼接
s1 = "hello"
s2 = "world"
s3 = "%s-%s" % (s1, s2)
print(s3)
方法四:format
连接
s1 = "hello"
s2 = "world"
s3 = "{0}-{1}".format(s1, s2)
print(s3)
方法五:string
模块的 Template
from string import Template
fruit1 = "apple"
fruit2 = "banana"
fruit3 = "pear"
str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table')
print(str.safe_substitute(fruit1=fruit1, fruit2=fruit2, fruit3=fruit3))
效率比较:+
号和 join
结论:join
的性能远高于 +
。
原因:
- 使用
+
进行字符串连接时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时,效率低下。 join
对多个字符进行连接时效率高,只会有一次内存的申请。
示例佐证:
import time
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print(end_time - start_time)
return wrapper
@decorator
def method_1():
s = ""
for i in range(1000000):
s += str(i)
@decorator
def method_2():
l = [str(i) for i in range(1000000)]
s = "".join(l)
method_1()
method_2()
结果:
1.940999984741211
0.2709999084472656
python字符串怎么和整数连接?
- 在 Python 中完成字符串和数字的拼接,可以使用内置函数
str()
。 - 在 Python 中如果直接对字符串和数字进行拼接,会发生报错。
- 使用内置函数
str()
转换类型。 - 使用
str()
对数值转换类型之后,可以正常运行。 - 在
print()
中使用逗号分隔打印数据,也可以解决字符串和数值连接的问题。
python怎么拼接字符串
Python拼接字符串一般有以下几种方法:
- 直接通过
+
操作符拼接:
使用这种方式进行字符串连接的操作效率低下,因为 Python 中使用输出结果: Hello World!
+
拼接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存。