How to concatenate string to specific format using Python?
Question:
Good morning,
I am a new python user and I am trying to replicate the following excel function in python:
=concatenate(left(H2,search(" ",H2,1)-1),if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=2,"00",if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=3,"0","")),right(H2,LEN(H2)-search(" ",H2,1)),"-KG")
I am trying to convert Highways into a format my computer program(arcgis) reads, basically turn my csv column format from:
the right column into the left column, so basically keep the two letter in the front (ex. US,FM,SL, CR) adding zeros in front making it a 4 digit highway always and adding "-KG" to the end.
thanks
Answers:
If using Python lists such as
arr = ['US 90', 'FM 1436', 'SL 305', 'US 277', 'FM 1589', 'SL 480']
do
result = [f'{s}{n:0>4}-KG' for s, n in map(str.split, arr)]
which gives
['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1589-KG', 'SL0480-KG']
This would look something like:
import csv
with open("yourfile.csv") as fp:
reader = csv.reader(fp, delimiter=" ")
output = [[' '.join(row),f'{row[0]}{row[1].zfill(4)}-KG'] for row in reader]
print(output)
[['US 50', 'US0050-KG'], ['CA 987', 'CA0987-KG'], ['IL 4', 'IL0004-KG']]
The zfill()
function will left pad a string with the 0
character to make the string the length of the argument (4
in this case)
If you are wanting to write that list of lists back out, check out this answer
This function converts the old highway format into your desired format:
def convert(highway):
split = highway.split()
prefix = split[0]
number = split[1]
return prefix + (4 - len(number))*"0" + number + "-KG"
If you’re working with a pandas dataframe, this converts your whole column:
import pandas as pd
highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]
df = pd.DataFrame(highways, columns=["Highways"])
df["Highways"] = df["Highways"].transform(convert, axis=0)
print(df)
Out:
Highways
0 US0090-KG
1 FM1436-KG
2 SL0305-KG
3 US0277-KG
4 FM1689-KG
5 SL0480-KG
Or if you’re using a list:
highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]
new_highways = [convert(highway) for highway in highways]
print(new_highways)
Out:
['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1689-KG', 'SL0480-KG']
You can try using the string format instead of zfill:
Here’s an example it’s not for csv but in arcgis I think you wanted to use it in the atributte calculator.
List= ['US 90','FM 1436','SL 305']
for elem in List:
Splited = str(elem).split(' ')
Concatenated_elem = str(Splited[0]) + f'{int(Splited[1]):04d}' +'-KG'
print(Concatenated_elem)
The result in this case is a print:
US0090-KG
FM1436-KG
SL0305-KG
Hope it helps,
Good morning,
I am a new python user and I am trying to replicate the following excel function in python:
=concatenate(left(H2,search(" ",H2,1)-1),if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=2,"00",if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=3,"0","")),right(H2,LEN(H2)-search(" ",H2,1)),"-KG")
I am trying to convert Highways into a format my computer program(arcgis) reads, basically turn my csv column format from:
the right column into the left column, so basically keep the two letter in the front (ex. US,FM,SL, CR) adding zeros in front making it a 4 digit highway always and adding "-KG" to the end.
thanks
If using Python lists such as
arr = ['US 90', 'FM 1436', 'SL 305', 'US 277', 'FM 1589', 'SL 480']
do
result = [f'{s}{n:0>4}-KG' for s, n in map(str.split, arr)]
which gives
['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1589-KG', 'SL0480-KG']
This would look something like:
import csv
with open("yourfile.csv") as fp:
reader = csv.reader(fp, delimiter=" ")
output = [[' '.join(row),f'{row[0]}{row[1].zfill(4)}-KG'] for row in reader]
print(output)
[['US 50', 'US0050-KG'], ['CA 987', 'CA0987-KG'], ['IL 4', 'IL0004-KG']]
The zfill()
function will left pad a string with the 0
character to make the string the length of the argument (4
in this case)
If you are wanting to write that list of lists back out, check out this answer
This function converts the old highway format into your desired format:
def convert(highway):
split = highway.split()
prefix = split[0]
number = split[1]
return prefix + (4 - len(number))*"0" + number + "-KG"
If you’re working with a pandas dataframe, this converts your whole column:
import pandas as pd
highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]
df = pd.DataFrame(highways, columns=["Highways"])
df["Highways"] = df["Highways"].transform(convert, axis=0)
print(df)
Out:
Highways
0 US0090-KG
1 FM1436-KG
2 SL0305-KG
3 US0277-KG
4 FM1689-KG
5 SL0480-KG
Or if you’re using a list:
highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]
new_highways = [convert(highway) for highway in highways]
print(new_highways)
Out:
['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1689-KG', 'SL0480-KG']
You can try using the string format instead of zfill:
Here’s an example it’s not for csv but in arcgis I think you wanted to use it in the atributte calculator.
List= ['US 90','FM 1436','SL 305']
for elem in List:
Splited = str(elem).split(' ')
Concatenated_elem = str(Splited[0]) + f'{int(Splited[1]):04d}' +'-KG'
print(Concatenated_elem)
The result in this case is a print:
US0090-KG
FM1436-KG
SL0305-KG
Hope it helps,