Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append string if not already present

Tags:

string

regex

ruby

I have strings of time (how poetic) from a third party and some have the timezone while others don't. What I'd like to do append a timezone if one isn't present.

Here are examples of strings with timezones...

5:21 AM MT
10:01 PM MT
8:41 PM MT

But sometimes that MT is missing for whatever reason.

So, what I need to do is append MT after AM or PM if it's missing.

(Note, I can't just check for MT. It could be any timezone. The primary goal here is to be able to append any timezone I choose after AM or PM).

like image 757
Shpigford Avatar asked Oct 30 '13 16:10

Shpigford


People also ask

How do I append to a string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

How do you append a string to a string in Python?

Method 1: Concatenate Strings Into a String using the += operator. This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task.

How do I add to the end of a string in Python?

If you want to add a string to the end of a string variable, use the += operator.


1 Answers

I didn't like any of these so I decided to just chomp it off if it exists and then add it again. In your case:

"#{time.chomp(' MT')} MT"

Edit: this doesn't actually work for OPs edited use case (many different time zones) but is useful for both the original use case and potentially people finding this from Google (like me!).

like image 186
RichieAHB Avatar answered Oct 06 '22 00:10

RichieAHB