Home > OS >  how to select a specific part of a string Django?
how to select a specific part of a string Django?

Time:07-16

I have strings in the database that are the names of countries and cities for example like this: Italy-Milan OR France-Paris. How can i select only the city part, like select what comes only after the '-' using python?

CodePudding user response:

you can split it by "-" and it will give an array of strings that are separated by "-".

data = "Italy-Milan"
values = data.split("-")
print(values[1])    #will print Milan in this case

CodePudding user response:

There are two ways, first is you do a bit of processing when making model in Django so just see how to do preprocessing for values in Django models. Another way is like if it's saved in db. You would do something like this.

User.city.split('-')[1] # -> changing it to zero will give France as answer, 

User is a model here. City will be containing your 'France-Paris'.

CodePudding user response:

If data is the variable having you city value and other info than to get only the city name

data.split("-")[1]

  • Related