Python Forum
Splitting strings in list of strings - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Splitting strings in list of strings (/thread-36541.html)



Splitting strings in list of strings - jesse68 - Mar-02-2022

Hi, trying to figure this one out which I expect should be easy. If I find my own solution before anyone else I'll post it here. I'm looking. Thanks

I have successfully split my line for values that were in quotes:

"val_1: val_2" "val_3: val_4" "val_5: val_6"

Now I have a list that contains: (which I think is a list of strings)

[ 'val_1: val_2' , 'val_3: val_4' , 'val_5: val_6']
How can I print the 2nd value in the pair separated by the colon :

To produce:

val_2 , val_4, val_6


RE: Splitting strings in list of strings - jesse68 - Mar-02-2022

Got it.

result = [ 'val_1: val_2' , 'val_3: val_4' , 'val_5: val_6']
for i in result:
    sword = i.split(':')
    print (sword[1])   
Result:

val_2
val_4
val_6
Yes?
Yes!


RE: Splitting strings in list of strings - Larz60+ - Mar-02-2022

Please show your code (enough for us to run, please)

What you show in the first list appears to be a dictionary represented as a list of strings.

If so the method of access of second item value is simple using original dictionary.
Need to see original form of data, prior to your conversion in order to determine if this is possible.


RE: Splitting strings in list of strings - DeaD_EyE - Mar-02-2022

I think a regex could help.

I used this regex: r"\s+?(\w+)\s+?:\s+?(\w+)"
On this line of text: " val_1 : val_2 val_3 : val_4 val_5 : val_6 "
I put the white spaces intentionally in this long string to make it harder.


You can the regex on https://regex101.com/
Don't forget to check Python as language.
The regex-string is on the top, and you must enter it without the leading r and the quotes.

The function re.findall will return all matching groups.
A dict can take this output.

Doing the same with str.split, str.strip etc. is a bit harder.
For myself, I didn't find a good solution without regex for this problem.

Often, the use of a regex can lead into the wrong direction.