If you are given a string consisting of numbers and Strings and want to add a space between them, you can use the following methods.
1. You can do it the naive way by sticking a string of spaces in between them. The variables count and conv need to be converted to string types to concatenate(join) them together. This is done with str().
2. Another way to add space between two variables and print the variables on the same line with a single space separating them is to use print(). If you need more spaces, you can add them to the string, and print(). The sample code for this method is as below. Call print(variable1, variable2) to print variable1 and variable2 with a space between them. The output is 8 7.36.
value1 = 8 value2 = 7.36 print(value1, value2)
3. You can use regex + sub() + lambda. This is another useful ways to solve the problem. Here, we also look for numerics to perform task of segregation. Sample code is as below.
# using regex + sub() import re # initializing string test_str = 'happy2happly is1for12happy' # 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))
In the above sample, the original string is happy2happly is1for12happy. Now, it is happy 2 happly is 1 for 12 happy.