在Python中,表示空格有以下几种常见的方法:
直接使用空格字符
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) 输出:Hello World
使用转义字符
import re
pattern = r'\s'
text = "Hello World"
matches = re.findall(pattern, text)
print(matches) 输出:[' ']
使用字符串方法
`split()` 方法:
words = "Hello World".split()
print(words) 输出:['Hello', 'World']
`join()` 方法:
words = ['Hello', 'World']
result = ' '.join(words)
print(result) 输出:Hello World
在函数定义和调用中使用空格
def add_numbers(a, b):
return a + b
total = add_numbers(3, 4)
print(total) 输出:7
写入空格到文件
with open('output.txt', 'w') as file:
file.write("Hello World")
以上是Python中表示和处理空格的一些常见方法。