简体   繁体   中英

Python String manipulation to store result in a string after removing comma delimiter

I have a string which I want to separate based on the ',' delimiter and store the result in a new string. Currently the split function stores the result in an array. How to store the result in a string with out the ',' delimiter? Also, I want to manipulate the positions of the string content. Are there ways in Python to do this?

code

string_in = "a,bcd,e1,20"
print (string_in.split())

output

['a,bcd,e1,20']

I want the below result to be stored in a string without the comma delimiter and manipulate the position of the string content as below.

   string_out = a bcd 20 e1

You want to pass your delimiter as an argument to split, like so:

>>> split = string_in.split(",")
['a', 'bcd', 'e1', '20']

That will give you a list of elements that you can manipulate as you wish. When you want to put them back into a space delimited string, you use join like so:

>>> " ".join(split)
'a bcd e1 20'

Take a look at the python documentation for split and join :

https://docs.python.org/3.8/library/stdtypes.html#str.split

https://docs.python.org/3.8/library/stdtypes.html#str.join

You are reinventing the wheel. In your case ordinary search /replace in source string suffices

string_in = "a,bcd,e1,20"
result = string_in.replace(',', ' ')

If you want split/join then

string_in = "a,bcd,e1,20"
result = ' '.join(string_in.split(','))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM