How do you split a string at a specific point?

I am new to python and want to break what I read from a text file into two specific parts. The following is an example of what can be read in:

f = ['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]

So what I want to achieve is to execute the second part of the program:

words = ['Cats','like','dogs','as','much','cats.']

numbers = [1,2,3,4,5,4,3,2,6]

I tried using:

words,numbers = f.split("][")

However, this removes double marriages from two new variables, which means that the second part of my program, which recreates the source code, does not work.

Thank.

+4
source share
6 answers

I assume that fis a string like

f = "['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]" 

then we can find the index ][and add it to find the point between the brackets

i = f.index('][')
a, b = f[:i+1], f[i+1:]
print(a)
print(b)

output:

['Cats','like','dogs','as','much','cats.']
[1,2,3,4,5,4,3,2,6]
+3
source

, split()

f = "['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]"
d="]["
print f.split(d)[0]+d[0]
print d[1]+f.split(d)[1]
+2

:

[["Cats","like","dogs","as","much","cats."],[1,2,3,4,5,4,3,2,6]]

Python json . , JSON , .

import json
f = '[["Cats","like","dogs","as","much","cats."],[1,2,3,4,5,4,3,2,6]]'
a, b = json.loads(f)
print(a)
print(b)

json : https://docs.python.org/3/library/json.html

+2

:

import re

data = "f = ['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]"
pattern = 'f = (?P<words>\[.*?\])(?P<numbers>\[.*?\])'

match = re.match(pattern, data)
words = match.group('words')
numbers = match.group('numbers')

print(words)
print(numbers)

['Cats','like','dogs','as','much','cats.']
[1,2,3,4,5,4,3,2,6]
+1

, , ['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6], . string.index() . . :

>>> f = open('./catsdogs12.txt', 'r')
>>> input = f.read()[:-1]  # Read file without trailing newline (\n)
>>> input
"['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]"
>>> bracket_index = input.index('][')  # Get index of transition between brackets
>>> bracket_index
41
>>> words = input[:bracket_index + 1]  # Slice from beginning of string
>>> words
"['Cats','like','dogs','as','much','cats.']"
>>> numbers = input[bracket_index + 1:]  # Slice from middle of string
>>> numbers
'[1,2,3,4,5,4,3,2,6]'

, python, (). , python (.. , ), string[1:-1].split(',') list.map() , .

, !

+1

, , - ] [ ] - [, "-" , split, , SPLIT
1. f = "['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]" 2. f= f.replace('][',']-[') 3. a,b =f.split('-')

O/P

  

print (a)
        "[" "," "," "," "," "," "."

     ()
        "[1,2,3,4,5,4,3,2,6]"

  


1. f = "[" "," "," "," "," "," ".] [1,2,3,4,5,4,3,2,6]"
2. f = f.replace('] [', '] - [')
3. a, b, c = f.partition('-')

O/P

  

print (a)
        "[" "," "," "," "," "," "."

     (c)
        "[1,2,3,4,5,4,3,2,6]"

  
+1
source

Source: https://habr.com/ru/post/1666028/


All Articles