I'm using R. Let's say I have a vector of cities and I want to use those city names individually in a string.
city = c("Dallas", "Houston", "El Paso", "Waco")
phrase = c("Hey {city}, what's the meaning of life?")
So I want to end up with four seperate phrases.
"Hey Dallas, what's the meaning of life?"
"Hey Houston, what's the meaning of life?"
...
Is there a function similar to format() in Python which will allow me to perform this task in a simple/efficient manner?
Would like to avoid something like below.
for( i in city){
phrase = c("Hey ", i, "what's the meaning of life?")
}
String objects are immutable - you cannot change their value - while doing assignments you are changing object to which the variable (or variable at given array index) is referring to. String[] fields = {firstNameField, lastNameField, firstName, lastName};
You can't assign strings. But you can call functions to help achieve what you want.
To assign it to a variable, we can use the variable name and “=” operator. Normally single and double quotes are used to assign a string with a single line of character but triple quotes are used to assign a string with multi-lines of character. This is how to declare and assign a variable to a string in Python.
How about sprintf
?
> city = c("Dallas", "Houston", "El Paso", "Waco")
> phrase = c("Hey %s, what's the meaning of life?")
> sprintf(phrase, city)
[1] "Hey Dallas, what's the meaning of life?" "Hey Houston, what's the meaning of life?"
[3] "Hey El Paso, what's the meaning of life?" "Hey Waco, what's the meaning of life?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With