How to insert a specific string between two words stored in a single variable?
Question:
I want to insert a string "and"
between two words of a string stored in a variable.
How can I achieve this in Python?
E.g.
Input string or input variable:
location = 'Location-1 Location-2 '
Expected Output:
location = 'Location-1 and Location-2'
But I don’t want to insert "and"
if the variable has single value
location = 'Location-1 '
or
location = 'Location-2 '
Answers:
You can use the string split()
and join()
methods:
location = 'Location-1 Location-2 '
location = ' and '.join(location.split())
print(repr(location))
Output:
'Location-1 and Location-2'
split()
splits a string into a list on a given delimiter, by default a whitespace. Since there is no string after the last whitespace, we also don’t need to use strip()
. join()
joins a list of strings using the string the method is called on.
I want to insert a string "and"
between two words of a string stored in a variable.
How can I achieve this in Python?
E.g.
Input string or input variable:
location = 'Location-1 Location-2 '
Expected Output:
location = 'Location-1 and Location-2'
But I don’t want to insert "and"
if the variable has single value
location = 'Location-1 '
or
location = 'Location-2 '
You can use the string split()
and join()
methods:
location = 'Location-1 Location-2 '
location = ' and '.join(location.split())
print(repr(location))
Output:
'Location-1 and Location-2'
split()
splits a string into a list on a given delimiter, by default a whitespace. Since there is no string after the last whitespace, we also don’t need to use strip()
. join()
joins a list of strings using the string the method is called on.