I am a beginner with R. Now, I have a vector in a data.frame like this
city
Kirkland,
Bethesda,
Wellington,
La Jolla,
Berkeley,
Costa, Evie KW172NJ
Miami,
Plano,
Sacramento,
Middletown,
Webster,
Houston,
Denver,
Kirkland,
Pinecrest,
Tarzana,
Boulder,
Westfield,
Fair Haven,
Royal Palm Beach, Fl
Westport,
Encino,
Oak Ridge,
I want to clean it. What I want is all the city names before the comma. How can I get the result in R? Thanks!
You can use gsub with a bit of regexp :
cities <- gsub("^(.*?),.*", "\\1", df$city)
This one works, too :
cities <- gsub(",.*$", "", df$city)
Just for fun, you can use strsplit
> x <- c("London, UK", "Paris, France", "New York, USA")
> sapply(strsplit(x, ","), "[", 1)
[1] "London" "Paris" "New York"
You could use regexpr to find the position of the first comma in each element and use substr to snip them at this:
x <- c("London, UK", "Paris, France", "New York, USA")
substr(x,1,regexpr(",",x)-1)
[1] "London" "Paris" "New York"
This works as well:
x <- c("London, UK", "Paris, France", "New York, USA")
library(qdap)
beg2char(x, ",")
## > beg2char(x, ",")
## [1] "London" "Paris" "New York"
If the this was a column in a dataframe, we can use tidyverse.
library(dplyr)
x <- c("London, UK", "Paris, France", "New York, USA")
x <- as.data.frame(x)
x %>% separate(x, c("A","B"), sep = ',')
A B
1 London UK
2 Paris France
3 New York USA
Related
so i made a list and i used tkinter for choosing a random data in list and showing that in a showinfo box. now i was just wondering if its possible to make a random image for random data.
for eg i am making a app that generates a random anime name from the list but i want to add the anime picture also is there any way i can do that ?
i haven't tried building it but here is what i have made so far.
i have no error i just want to have different picture for different names from the list chose randomly
import random
from tkinter import*
from tkinter import messagebox
anime = [
"1 Ore ga Ojousama Gakkou ni ' Shomin Sample' Toshite Gets♥Sareta Ken",
"2 Ookami to Koushinryou II",
"3 Ookami to Koushinryou",
"4 Grisaia no Kajitsu",
"5 Nyanko Days",
"6 Suzumiya Haruhi no Shoushitsu",
"7 Ookami Kodomo no Ame to Yuki",
"8 Sankarea",
"9 Boku no Hero Academia the Movie 2: Heroes Rising",
"10 Tensei shitara Slime Datta Ken OVA",
"11 Nakitai Watashi wa Neko wo Kaburu ",
"12 Tensei shitara Slime Datta Ken",
"13 Nande Koko ni Sensei ga!?",
"14 Kotonoha no Niwa",
"15 Chuunibyou demo Koi ga Shitai! Movie: Take On Me",
"16 Byousoku 5 Centimeter",
"17 Summer Wars",
"18 Tenki no Ko ",
"19 Kimi no Na wa.",
"20 Sword Art Online: Alicization – War of Underworld",
"21 Hinamatsuri",
"22 Gakuen Babysitters ",
"23 Yahari Ore no Seishun Love Comedy wa Machigatteiru. Zoku",
"24 Yahari Ore no Seishun Love Comedy wa Machigatteiru.",
"25 Hataraku Maou-sama!",
"26 Shokugeki no Souma: Shin no Sara",
"27 Shokugeki no Souma: San no Sara – Toutsuki Ressha-hen",
"28 Sewayaki Kitsune no Senko-san",
"29 Shokugeki no Souma: San no Sara",
"30 Shokugeki no Souma: Ni no Sara",
"31 Shokugeki no Soma ",
"32 Ao no Exorcist ",
"33 Ao no Exorcist: Kyoto Fujouou-hen",
"34 Boku dake ga Inai Machi",
"35 Kono Subarashii Sekai ni Shukufuku wo!: Kurenai Densetsu",
"36 Hyouka",
"37 Kami no Tou",
"38 Youkoso Jitsuryoku Shijou Shugi no Kyoushitsu e",
"39 Shingeki no Kyojin Season 3",
"40 Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen 2nd Season",
"41 Shingeki no Kyojin Season 3 Part 2",
"42 Shingeki no Kyojin Season 2",
"43 Shingeki no Kyojin ",
"44 Kono Subarashii Sekai ni Shukufuku wo! 2",
"45 Seishun Buta Yarou wa Yumemiru Shoujo no Yume wo Minai",
"46 Kono Subarashii Sekai ni Shukufuku wo!",
"47 Seishun Buta Yarou wa Bunny Girl Senpai no Yume wo Minai",
"48 Sakurasou no Pet na Kanojo",
"49 Tate no Yuusha no Nariagari",
"50 IS: Infinite Stratos",
"51 Kawaikereba Hentai demo Suki ni Natte Kuremasu ka?",
"52 Enen no Shouboutai",
"53 Kaguya-sama wa Kokurasetai: Tensai-tachi no Renai Zunousen",
"54 Chuunibyou demo Koi ga Shitai! Ren",
"55 Koe no Katachi ",
"56 Dr. Stone",
"57 One Punch Man",
"58 Naruto Shippuden",
"59 Sword Art Online II",
"60 Sword Art Online",
"61 Ansatsu Kyoushitsu 2nd season",
"62 Ansatsu Kyoushitsu",
"63 Chuunibyou demo Koi ga Shitai!",
"64 Kimetsu no Yaiba",
"65 Re:Zero kara Hajimeru Isekai Seikatsu",
"66 Nanatsu no Taizai",
"67 Steins;Gate 0",
"68 Steins;Gate",
"69 Nanatsu no Taizai: Imashime no Fukkatsu",
"70 Tokyo Ghoul √A",
"71 One Punch Man Season 2",
"72 Hunter x Hunter (2011)",
"73 Darling in the FranXX",
"74 Tokyo Ghoul",
"75 Boku no Hero Academia 3rd Season.",
"76 Boku no Hero Academia",
"77 Nanatsu no Taizai: Kamigami no Gekirin",
"78 Naruto",
"79 Boku no Hero Academia 4th Season",
"80 Arte",
"81 Yakusoku no Neverland",
"82 Aho Girl",
"83 Wotaku ni Koi wa Muzukashii",
"84 Kimi no Suizou wo Tabetai ",
"85 Sakasama no Patema",
"86 Grisaia no Rakuen",
"87 Kimi ni Todoke",
"88 Kimi ni Todoke 2nd Season",
"89 Sukitte Ii na yo.",
"90 Ore wo Suki nano wa Omae dake ka yo",
"91 Koi To Uso",
"92 Saijaku Muhai no Bahamut",
"93 7 seeds",
"94 7 Seeds 2nd Season",
"95 Kono Yo no Hate de Koi wo Utau Shoujo YU-NO",
"96 Gotoubun no Hanayome",
"97 Masamune-kun no Revenge",
"98 Tokyo Magnitude 8.0",
"99 Keppeki Danshi! Aoyama-kun Episode ",
"100 Ao Haru Ride",
"101 Kakegurui",
"102 Kakegurui××",
"103 Tokyo Ghoul:re",
"104 Tokyo Ghoul:re 2nd season",
"105 Toradora!",
"106 Sounan Desu ka?",
"107 Denpa Onna to Seishun Otoko",
"108 Zenonzard The Animation",
"109 Hanamaru Kindergarden",
"110 Tonari no Kaibutsu-kun",
"111 Domestic na Kanojo",
"112 Haikyuu!!",
"113 Haikyuu!! Second Season",
"114 Haikyuu!!: Karasuno Koukou vs. Shiratorizawa Gakuen Koukou",
"115 Haikyuu!!: To the Top",
"116 Sword Art Online: Alicization – War of Underworld 2nd Season",
"117 Haikyuu!!: To the Top",
"118 Yahari Ore no Seishun Love Comedy wa Machigatteiru. Kan",
"119 Kanojo, Okarishimasu",
"120 Shokugeki no Souma: Gou no Sara",
"121 Maou Gakuin no Futekigousha: Shijou Saikyou no Maou no Shiso, Tensei shite Shison-tachi no Gakkou e",
"122 UZAKI-CHAN WA ASOBITAI!",
"123 ReLIFE",
"124 ReLIFE: Kanketsu-hen",
"125 The God of High School",
"126 Inou-Battle wa Nichijou-kei no Naka de",
"127 Kyoukai no Kanata",
"128 Arifureta Shokugyou de Sekai Saikyou",
"129 ISEKAI MAOU TO SHOUKAN SHOUJO NO DOREI MAJUTSU",
"130 AKAME GA KILL!",
"131 Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season",
"132 Shinchou Yuusha: Kono Yuusha ga Ore Tueee Kuse ni Shinchou Sugiru",
"133 Noragami",
"134 Noragami OVA",
"135 Noragami Aragoto",
"136 Nisekoi",
"137 Nisekoi:",
"138 Black Bullet",
"139 Devils Line",
"140 TABOO TATTOO",
"141 Hajimete no Gal ",
"142 Kuzu no Honkai",
"143 Tsurezure Children",
"144 Himouto! Umaru-chan",
"145 Boku no Kanojo ga Majimesugiru Sho-bitch na Ken",
"146 Bungou Stray Dogs",
"147 Bungou Stray Dogs Season 2",
"148 Bungou Stray Dogs 3rd Season",
"149 Lovely★Complex",
"150 Plunderer",
"151 TONIKAKU KAWAII",
"152 Enen no Shouboutai: Ni no Shou",
"153 Haikyuu!!: To the Top 2nd Season",
"154 Shigatsu wa Kimi no Uso",
"155 Kaichou wa Maid-sama",
"156 Karakai Jouzu no Takagi-san",
"157 Karakai Jouzu no Takagi-san 2"]
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Anime", random.choice(anime))
can = Canvas(top, height = 100, width = 100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
b1 = Button(can,text = "Generate",command = fun,activeforeground = "black",activebackground = "yellow",pady=10)
b1.pack(side = TOP)
top.mainloop()
Since you want the image to be corresponding to the anime titles I suggest you use a dictionary instead of a list. Also, use Toplevel widget to display the output.
So here is an example code:
import random
from tkinter import*
from PIL import Image, ImageTk
absolute_path = r'C:\Users\ ' # your absolute path goes here(Note: Don't remove the extra space in the end)
anime = {
"1 Ore ga Ojousama Gakkou ni ' Shomin Sample' Toshite Gets♥Sareta Ken": 'Akira.png', # anime image name
"2 Ookami to Koushinryou II": 'Alex.jpg', # anime image name
}
root = Tk()
root.geometry("200x100")
def fun():
top = Toplevel(root)
top.title('Anime')
random_choice = random.choice(list(anime.keys())) #choosing random from dictionary keys
label = Label(top, text=random_choice)
label.pack()
top.img = ImageTk.PhotoImage(Image.open(absolute_path.strip()+anime[random_choice]))
image_label = Label(top, image=top.img)
image_label.pack()
can = Canvas(root, height = 100, width = 100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)
b1 = Button(can,text = "Generate",command = fun,activeforeground = "black",activebackground = "yellow",pady=10)
b1.pack(side = TOP)
root.mainloop()
Here is the code:
import time
from colored import fg
import sys
clr1 = fg("red")
clr2 = fg("blue")
clr3 = fg("yellow")
clr4 = fg("green")
for x in (clr1 + "Hi,\nThis program is made to find out the capital city of countries. For now, there are only around 100 countries which you can find the capitals of.\nThe countries are:\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.03)
time.sleep(1)
for x in (clr2 + "Afghanistan\nAlbania\nAlgeria\nArgentina\nArmenia\nAustralia\nAustria\nAzerbaijan\nBahrain\nBangladesh\nBelgium\nBenin\nBotswana\nBrazil\nBulgaria\nCanada\nChile\nColombia\nCostaRica\nCroatia\nCuba\nDenmark\nDjibouti\nDominica\nEgypt\nEritrea\nEstonia\nEthiopia\nFiji\nFinland\nFrance\nGabon\nGermnay\nGhana\nGreece\nGrenada\nGuinea\nHaiti\nHungary\nIceland\nIndia\nIndonesia\nIran\Ireland\nItaly\nJamaica\nJapan\nJordan\nKenya\nSouthKorea\nKosovo\nKuwait\nLaos\nLativa\nLebanon\nLiberia\nLibya\nLuxembourg\nMacedonia\nMadagascar\nMalawi\nMalaysia\nMaldives\nMali\nMexico\nMoldova\nMonaco\nMongolia\nMontenegro\nMorocco\nMozambique\nNamibia\nNepal\nNetherlands\nNewZealand\nNiger\nNigeria\nNorway\nOman\nPakistan\nPanama\nPhilippines\nPoland\nPortugal\nQatar\nRomania\nRussia\nSamoa\nSaudi Arabia\nSenegal\nSerbia\nSingapore\nSlovakia\nSomalia\nSouth Africa\nSpain\nSri Lanka\nSudan\nSwitzerland\nSyria\nTaiwan\nThailand\nUganda\nUnited Arab Emirates\nUnited Kingdom\nUnited States of America\nUruguay\nVatican City\nVietnam\nYemen\nZimbabwe\n\n\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.003)
time.sleep(1)
countries = {
"Afghanistan": 'Kabul',
"Albania":'Tirana',
"Algeria":'Algeirs',
"Argentina":'Buenos Aires',
"Armenia":'Yerevan',
"Australia":'Cnaberra',
"Austria":'Vienna',
"Azerbaijan":'Baku',
"Bahrain":'Manama',
"Bangladesh":'Dhaka',
"Belgium":'Brussels',
"Benin":'Porto_Novo',
"Botswana":'Gaborone',
"Brazil":'Brasilia',
"Bulgaria":'Sofia',
"Canada":'Ottawa',
"Chile":'Santiago',
"Colombia":'Bogota',
"Costa Rica":'San Jose',
"Croatia":'Zagreb',
"Cuba":'Havana',
"Denmark":'Copenhagen',
"Djibouti":'Djibouti',
"Dominica":'Roseau',
"Egypt":'Cairo',
"Eritrea":'Asmara',
"Estonia":'Tallinn',
"Ethiopia":'Addis Ababa',
"Fiji":'Suva',
"Finland":'Helsinki',
"France":'Paris',
"Gabon":'Libreville',
"Germnay":'Berlin',
"Ghana":'Accra',
"Greece":'Athens',
"Grenada":'Saint Georges',
"Guinea":'Conakry',
"Haiti":'Port-au-Prince',
"Hungary":'Budapest',
"Iceland":'Reykjavik',
"India":'New Delhi',
"Indonesia":'Jakarta',
"Iran":'Tehran',
"Ireland":'Dublin',
"Italy":'Rome',
"Jamaica":'Kingston',
"Japan":'Tokyo',
"Jordan":'Amman',
"Kenya":'Nairobi',
"South Korea":'Seoul',
"Kosovo":'Pristina',
"Kuwait":'Kuwait City',
"Laos":'Vientiane',
"Lativa":'Riga',
"Lebanon":'Beirut',
"Liberia":'Monrovia',
"Libya":'Tripoli',
"Luxembourg":'Luxembourg',
"Macedonia":'Skopje',
"Madagascar":'Antananarivo',
"Malawi":'Lilongwe',
"Malaysia":'Kuala Lumpur',
"Maldives":'Male',
"Mali":'Bamako',
"Mexico":'Mexico City',
"Moldova":'Chisnau',
"Monaco":'Monaco',
"Mongolia":'Ulaanbaatar',
"Montenegro":'Podgorica',
"Morocco":'Rabat',
"Mozambique":'Maputo',
"Namibia":'Windhoek',
"Nepal":'Kathmandu',
"Netherlands":'Amsterdam',
"NewZealand":'Wellington',
"Niger":'Niamey',
"Nigeria":'Abuja',
"Norway":'Oslo',
"Oman":'Muscat',
"Pakistan":'Islamabad',
"Panama":'Panama City',
"Philippines":'Manila',
"Poland":'Warsaw',
"Portugal":'Lisbon',
"Qatar":'Doha',
"Romania":'Bucharest',
"Russia":'Moscow',
"Samoa":'Apia',
"Saudi Arabia":'Riyadh',
"Senegal":'Dakar',
"Serbia":'Belgrade',
"Singapore":'Singapore',
"Slovakia":'Bratislava',
"Somalia":'Mogadishu',
"South Africa":'Pretoria(administrative); Cape Town(legislative); Bloemfontein(judicary)',
"Spain":'Madrid',
"Sri Lanka":'Colombo; Sri Jayewardenepura Kotte(legislative)',
"Sudan":'Khartoum',
"Switzerland":'Bern',
"Syria":'Damascus',
"Taiwan":'Taipei',
"Thailand":'Bangkok or Krung Thep Maha Nakhon',
"Uganda":'Kampala',
"United Arab Emirates":'Abu Dhabi',
"United Kingdom":'London',
"United States of America":'Washington, D.C',
"Uruguay":'Montevideo',
"Vatican City":'Vatican City',
"Vietnam":'Hanoi',
"Yemen":'Sanaa',
"Zimbabwe":'Harare'
}
time.sleep(1)
user_input = input(clr3 + "What country's capital do you want to find out (That is in the list) ?\n>>> ")
So every time the user inputs a country, how do I make it so that it prints out the capital with the fewest possible lines of code. For example i enter France and it gives out Paris. I dont want to use if statements to go through every line and say if user_input == <> : print("Capital"). That way I will have to write the statements over a 100 times. Is there a way to solve this problem
try:
print(countries[user_input])
except KeyError: # If the user input wasn't found in the dictionary
print("Invalid Country!")
I am trying to go through a column of data frame in python 3. What I need to do is take from each row the country that it is mentioned and the number of times that country is mentioned.
i.e. if I have this row:
['[Aydemir, Deniz', ' Gunduz, Gokhan', ' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey', ' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden']
it needs to output a list: ['Turkey', 'Sweden']
and if I have this row:
['[Fang, Qun', ' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China', ' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China']
the output should be: ['China', 'China'].
I have written this code but it is not working as I want to:
from geotext import GeoText
sentence = df.iloc[0,0]
places = GeoText(sentence)
print(places.countries)
It prints only the country once and in some cases when it is USA it doesn't recognize the abbreviation. Can you help me figure out what to do?
l = [['[Aydemir, Deniz\', \' Gunduz, Gokhan\', \' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey\', \' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden',1990],
['[Fang, Qun\', \' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China\', \' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China',2005],
['[Blumentritt, Melanie\', \' Gardner, Douglas J.\', \' Shaler, Stephen M.] Univ Maine, Sch Resources, Orono, ME USA\', \' [Cole, Barbara J. W.] Univ Maine, Dept Chem, Orono, ME 04469 USA',2012]]
dataf = pd.DataFrame(l, columns = ['Authors', 'Year'])
I tried to do this code but I have the same problem, it doesn't give all the counties only one per row:
def find_country(n):
for c in pycountry.countries:
if str(c.name).lower() in n.lower():
return c.name
country1 = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: find_country(x)))
USA does not seem to be detected correctly by geotext - it's worth trying to raise an issue with that package. As a workaround here, I replace USA with United States, which is correctly detected.
df = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: geotext.GeoText(x).countries)
)
I'm not sure what you were doing before, but this will get the list of countries for each of the rows in Author, including duplicates.
0 [Turkey, Sweden]
1 [China, China]
2 [United States, United States]
Name: Authors, dtype: object
As mentioned in the comment, if you want to have an actual list of lists, just add tolist() to the end.
df.tolist()
[['Turkey', 'Sweden'], ['China', 'China'], ['United States', 'United States']]
I am needing to convert a list of lists of strings into a three column table where the first column is 1 space longer than the longest string. I have figured out how to identify the longest string and how long it is, but getting the table to form has been quite tricky. Here is the program with the lists in it and it shows you that the longest one is 26 characters long.
def main():
mycities = [['Cape Girardeau', 'MO', '63780'], ['Columbia', 'MO', '65201'],
['Kansas City', 'MO', '64108'], ['Rolla', 'MO', '65402'],
['Springfield', 'MO', '65897'], ['St Joseph', 'MO', '64504'],
['St Louis', 'MO', '63111'], ['Ames', 'IA', '50010'], ['Enid',
'OK', '73773'], ['West Palm Beach', 'FL', '33412'],
['International Falls', 'MN', '56649'], ['Frostbite Falls',
'MN', '56650']]
col_width = max(len(item) for sub in mycities for item in sub)
print(col_width)
main()
Now I am just needing to get it to print off like this:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650
You're off to the right start -- as an example given the specific structure to the lists you have, you can use the col_width you calculated to determine the number of spaces you'd need after the name of each city to append to the end of each city name:
for city in mycities:
# append the string with the number of spaces required
city_padded = city[0] + " " + " "*(col_width-len(city[0]))
print(city_padded + city[1] + " " + city[2])
Given your example, this will produce:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Rolla MO 65402
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650
Note in the original version of your question, you are missing commas in your sublists in your mycities variable, for which I've added in an edit.
As a side note, it is convention in Python that words be separated by underscores in variable names for readability, so you might rename mycities to my_cities.
pep8 ref: (https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)
"String name".ljust(26) will add spaces to the end of your string. For example,
Ames.ljust(26) will result in 'Ames (22 spaces here)', and then the next column will print after. If you are not sure what the longest city will be, you could replace the 26 with len(cities[-1]) after ordering the cities in a list by length. To do this, you can do sortedCities = sorted(cityListVariable, key=len)
def main():
cities = ['Cape Girardeau, MO 63780', 'Columbia, MO 65201', 'Kansas City, MO 64108', 'Rolla, MO 65402',
'Springfield, MO 65897', 'St Joseph, MO 64504', 'St Louis, MO 63111', 'Ames, IA 50010',
'Enid, OK 73773', 'West Palm Beach, FL 33412', 'International Falls, MN 56649', 'Frostbite Falls, MN 56650',
'Charlotte, NC 28241', 'Upper Marlboro, MD 20774', 'Camdenton, MO 65020', 'San Fransisco, CA 94016'] #create list of information
for x in cities:
col = x.split(",")
if(len(col) == 2):
city = col[0].strip()
temp = col[1].strip()
else:
city = x[:15].strip()
temp = c[15:].strip()
state = temp[:2]
zipCode = int(temp[-5::])
print("%-20s\t%s\t%d"%(city, state, zipCode))
main()
I have a bunch of addresses:
123 Main Street, PO Box 345, Chicago, IL 92921
1992 Super Way, Bakersfield, CA
234 Wonderland Lane, Attn: Daffy Duck, Orlando, FL 09922
How could I cut out the second string in there, when I do myStr.split(',') on each?
The idea is that I want to return:
123 Main Street, Chicago, IL 92921
1992 Super Way, CA
234 Wonderland Lane, Orlando, FL 09922
I could loop through each part, and build yet another string, skipping the second index, but was wondering if there's a better way to do so.
What I have now:
def filter_address(address):
print("Filtering address on",address)
updated_addr = ""
indx = 0
for section in address.split(","):
if indx != 1:
updated_addr = updated_addr + "," + section
indx += 1
updated_addr = updated_addr[1:] # This is to remove the leading `,`
new_address = filter_address("123 Main Street, Chicago, IL 92921")
You could use del in python and glue back the components of the string with ", " after splitting them.
For example:
address = "123 Main Street, PO Box 345, Chicago, IL 92921".split(",")
del address[1]
pretty_address = ", ".join(address)
print(pretty_address) # Gives 123 Main Street, Chicago, IL 92921