欢迎访问宙启技术站
智能推送

10个Python函数-学会字符串拼接的艺术

发布时间:2023-05-25 23:54:11

1. join()

join()函数是Python中用来连接字符串的经典函数。使用如下:

'''string_name = separator.join(iterable)'''

其中,separator是指字符串之间的分隔符,iterable是指可迭代的对象,如列表、元组、字符串等。代码示例:

words = ['hello', 'world', 'this', 'is', 'python']
separator = ' '
result = separator.join(words)
print(result)   # 输出:hello world this is python

2. format()

format()函数可以方便地将变量值插入特定的字符串中。使用如下:

'''string_name = "My name is {} and I am {} years old".format(name, age)'''

其中,字符串中的大括号{}表示占位符,分别对应format()函数中传入的参数。代码示例:

name = 'Tom'
age = 20
result = "My name is {} and I am {} years old".format(name, age)
print(result)   # 输出:My name is Tom and I am 20 years old

3. f-strings

f-strings是Python 3.6版本新增的字符串格式化方式,使用起来非常方便。使用如下:

'''string_name = f"My name is {name} and I am {age} years old"'''

其中,字符串中的大括号{}表示占位符,内部可以嵌入变量和表达式。代码示例:

name = 'Tom'
age = 20
result = f"My name is {name} and I am {age} years old"
print(result)   # 输出:My name is Tom and I am 20 years old

4. replace()

replace()函数用于将字符串中的子串替换为新的子串。使用如下:

'''string_name = old_string.replace(old_substring, new_substring)'''

其中,old_substring指待替换的旧子串,new_substring指新子串。代码示例:

string = 'hello world'
new_string = string.replace('world', 'python')
print(new_string)   # 输出:hello python

5. capitalize()

capitalize()函数用于将字符串的 个字符转换为大写字母。使用如下:

'''string_name = old_string.capitalize()'''

代码示例:

string = 'hello world'
new_string = string.capitalize()
print(new_string)   # 输出:Hello world

6. split()

split()函数用于将字符串分割为一个字符串列表。默认情况下,分隔符为所有空字符,包括空格、换行符、制表符等。使用如下:

'''string_list = string.split(separator)'''

其中separator是指分隔符,默认为空格。代码示例:

string = 'hello world'
string_list = string.split()
print(string_list)   # 输出:['hello', 'world']

7. strip()

strip()函数可以用来去除字符串两端的空格或特定的字符。使用如下:

'''string_name = old_string.strip()'''

代码示例:

string = '    hello world   '
new_string = string.strip()
print(new_string)   # 输出:hello world

8. center()

center()函数可以用来居中对齐字符串。使用如下:

'''string_name = old_string.center(width, char)'''

其中,width是指总宽度,char是指填充的字符,默认为空格。代码示例:

string = 'hello'
new_string = string.center(10, '*')
print(new_string)   # 输出:**hello***

9. find()

find()函数用于在字符串中查找子串出现的位置。如果找到了,返回子串的 个字符的位置;如果找不到,返回-1。使用如下:

'''position = string.find(substring)'''

代码示例:

string = 'hello world'
position = string.find('world')
print(position)   # 输出:6

10. count()

count()函数用于统计字符串中某个子串出现的次数。使用如下:

'''count = string.count(substring)'''

代码示例:

string = 'hello world'
count = string.count('o')
print(count)   # 输出:2

字符串拼接在Python编程中是非常常见而重要的操作。使用上述这些函数,可以让Python程序员更加高效地进行字符串拼接。