Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right and elegant way to split a join a string in Python

I have the following list:

>>> poly
'C:\\04-las_clip_inside_area\\16x16grids_1pp_fsa.shp'
>>> record
1373155

and I wish to create:

'C:\\04-las_clip_inside_area\\16x16grids_1pp_fsa_1373155.txt'

I wish to split in order to get the part "C:\04-las_clip_inside_area\16x16grids_1pp_fsa16x16grids_1pp_fsa".

I have tried this two-code-lines solution:

mylist = [poly.split(".")[0], "_", record, ".txt"]
>>> mylist
['C:\\04-las_clip_inside_area\\16x16grids_1pp_fsa', '_', 1373155, '.txt']

from here, reading the example in Python join, why is it string.join(list) instead of list.join(string)?.

I find this solution to joint, but I get this error message:

>>> mylist.join("")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

Also if I use:

>>> "".join(mylist)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: sequence item 2: expected string, int found
like image 352
Gianni Spear Avatar asked Oct 11 '12 13:10

Gianni Spear


People also ask

How do you split a joined string in Python?

Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator.

What is the best way to split a string in Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

What split () & join () method Why & Where it is used?

The split() method splits a String object into an array of strings by separating the string into substrings. The splice() method changes the content of an array by removing existing elements and/or adding new elements. The join() method joins all elements of an array into a string.

How do you split a string with special characters in Python?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.


1 Answers

Python join: why is it string.join(list) instead of list.join(string)?

So there is

"".join(mylist)

instead of

mylist.join("")

There's your error.

To solve your int/string problem, convert the int to string:

mylist= [poly.split(".")[0],"_",str(record),".txt"]

or write directly:

"{}_{}.txt".format(poly.split(".")[0], record)
like image 166
eumiro Avatar answered Oct 11 '22 09:10

eumiro