Home > Software engineering >  Python string operations to generate date format
Python string operations to generate date format

Time:10-03

I am using the below code to generate a variable that can be used in my code: value of year_current is 21

Code:

month_1 = "Jan '"
month_2 = "Dec '"
'"'   month_1   str(year_current)   '":"'  month_2   str(year_current)   '"'

The output generated by the above code is :

"Jan \'21":"Dec \'21"

I do not want the "" symbol in the output. What can be done to avoid that?

Expected output:

"Jan '21":"Dec '21" (with all the quotes intact so that I can use this in df.loc)

I have also used the below approach:

Code:

month_1 = "'Jan '"
month_2 = ":'Dec '"
month_1  str(year_current) "'"  month_2  str(year_current) "'"

This gives me the output:

'Jan '21':'Dec '21'

But then it creates confusion in the code with respect to single quotes. Hence this does not work for me.

Not sure if its due to my code being in Jupyter but solution is not working as expected:

enter image description here

CodePudding user response:

In this case you could use f-string.

Try this:

month_1 = "Jan '"
month_2 = "Dec '"
year_current = 21
#year_current = pd.Timestamp.today().strftime('%y') #if you dont want hardcord year

month_str = f'"{month_1}{year_current}":"{month_2}{year_current}"'

print(month_str)

Output:

"Jan '21":"Dec '21"

CodePudding user response:

You can use f strings as below it is much more convenient for string formatting.

year_current = '21'
month_1 = "Jan '"
month_2 = "Dec '"
output  = f"\"{month_1}{year_current}\":\"{month_2}{year_current}\""
print(output)
  • Related