'Fetching elements from a list with spaces in between the string (Python) [duplicate]
I am trying to write a function which can remove leading spaces and replace spaces in between the string with ',' and then split the string by ',' to individual elements.
split_entry = ['ENTRY', ' 102725023 CDS T01001']
res = []
def ws(list):
for x in split_entry:
entry_info = x.lstrip() #remove leading spaces at the start of string (' 102725023)
entry_info = re.sub('\s+',', ',entry_info) #replaces multiple spaces with ',' within a string
if(re.search("^\d+",entry_info)): #if element starts with digits '102725023'
l = entry_info.split(", ", entry_info) #split by ','
print (l[0]) #get first element
#return l[0]
ws(split_entry)
I would like to get the first element of the second list element (102725023 ). However I am getting following error while running above code.
TypeError: 'str' object cannot be interpreted as an integer
Any suggestions to resolve it. Thanks
Solution 1:[1]
You don't actually need to manually remove spaces your self - Python's split function can handle multiple spaces
After that, you can join the List to get a comma-separated string
a = 'fa fdsa f'
b = a.split()
print(b) # ['fa', 'fdsa', 'f']
print(",".join(b)) # 'fa,fdsa,f'
As for your code, there are a couple things:
- Don't name your variable or parameter
listbecause it is a reserved keyword in Python - In your
wsfunction, you should usefor x in parameterList, not explicitly statingsplit_entry
But honestly I am not entirely sure what exactly is wrong either.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
