Python – 在字符串中的数字和字母之间添加空格
给定一个由数字和字符串组成的字符串,在它们之间添加空格。
Input : test_str = ‘ge3eks4geeks is1for10geeks’
Output : ge 3 eks 4 geeks is 1 for 10 geeks
Explanation : Numbers separated from Characters.
Input : test_str = ‘ge3eks4geeks’
Output : ge 3 eks 4 geeks
Explanation : Numbers separated from Characters by space.
方法 #1:使用正则表达式 + sub() + lambda
在此,我们通过适当的正则表达式执行查找字母的任务,然后使用 sub() 进行替换,lambda 执行在其间添加空格的任务。
Python3
# Python3 code to demonstrate working of
# Add space between Numbers and Alphabets in String
# using regex + sub() + lambda
import re
# initializing string
test_str = 'geeks4geeks is1for10geeks'
# printing original String
print("The original string is : " + str(test_str))
# using sub() to solve the problem, lambda used tp add spaces
res = re.sub("[A-Za-z]+", lambda ele: " " + ele[0] + " ", test_str)
# printing result
print("The space added string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Add space between Numbers and Alphabets in String
# using regex + sub()
import re
# initializing string
test_str = 'geeks4geeks is1for10geeks'
# printing original String
print("The original string is : " + str(test_str))
# using sub() to solve the problem, lambda used tp add spaces
res = re.sub('(\d+(\.\d+)?)', r' \1 ', test_str)
# printing result
print("The space added string : " + str(res))
输出
The original string is : geeks4geeks is1for10geeks
The space added string : geeks 4 geeks is 1 for 10 geeks
方法#2:使用正则表达式 + sub()
这是解决的方法之一。在此,我们寻找数字而不是字母来执行隔离任务,类似的方法是使用数字作为添加空格的搜索条件。
Python3
# Python3 code to demonstrate working of
# Add space between Numbers and Alphabets in String
# using regex + sub()
import re
# initializing string
test_str = 'geeks4geeks is1for10geeks'
# printing original String
print("The original string is : " + str(test_str))
# using sub() to solve the problem, lambda used tp add spaces
res = re.sub('(\d+(\.\d+)?)', r' \1 ', test_str)
# printing result
print("The space added string : " + str(res))
输出
The original string is : geeks4geeks is1for10geeks
The space added string : geeks 4 geeks is 1 for 10 geeks