Skip to content
Advertisement

How to access first n characters of a key value in Python

I need to access the first 10 characters of a key-value in dictionary. My dictionary looks like this:

data = {"id": "bob", "start_date": "2020-01-01 00:00:00"}

I have tried:

for key, value in data.items():
    new_start = data["start_date"][0,10]

The desired output is:

print new_start
2020-01-01

Advertisement

Answer

Why are you using a loop? You can do this directly:-

print(date['start_date'][0:10])

Output:-

'2020-01-01'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement