简体   繁体   中英

Move a character or word to a new line

Given a string how do i move part of the string in to a new line. without moving the rest of the line or characters

'This' and 'this' word should go in the next line
Output:
> and word should go in the next line
  This this

This is just an example of the output i want assuming the words can be different by characters. To be more clear say i have some string elements in an array and i have to move every second and third word of the elements to a new line and printing the rest of the line as is. I've tried using \\n and a for loop. But it also moves the rest of the string to a new line

['This and this', 'word should go', 'in the next']
Output:
> This word in
  and this should go the next

So the 2nd and 3rd word of the elements are moved without affecting the rest of the line. Is it possible to do this without much complication? I'm aware of the format method but i don't know how to use it in this situation.

For your first example, in case you don't know the order of the target words in advance, I would use a dictionary to store the indices of the found words. Then you can sort those to put the found words in the second line in the same order as they appeared in the text:

targets = ['this', 'This']
source = 'This and this word should go in the next line.'

target_ixs = {source.find(target): target for target in targets}
line2 = ' '.join([target_ixs[i] for i in sorted(target_ixs)])

line1 = source
for target in targets:
    line1 = line1.replace(target, '')
line1 = line1.replace('  ', ' ').lstrip()

result = line1 + '\n' + line2
print(result)
and word should go in the next line.
This this

Your second example is easier, because you already know which parts of the strings to put in the second line, so you just need to split each string into a list of words and select from those:

source = ['This and this', 'word should go', 'in the next']

source_lists = [s.split() for s in source]
line1 = ' '.join([source_list[0] for source_list in source_lists])
line2 = ' '.join([' '.join(source_list[1:]) for source_list in source_lists])

result = line1 + '\n' + line2
print(result)
This word in
and this should go the next

You can probably do quite a bit without much complication using the regular expression library and some python language features. That being said, it depends on how complex the rules are for determining what words go where. Typically, you want to start with a string and "tokenize" it into the constituent words. See the code example below:

import re
sentence = "This and this word should go in the next line"

all_words = re.split(r'\W+', sentence)
matched_words = " ".join(re.findall(r"this", sentence, re.IGNORECASE))
unmatched_words = " ".join([word for word in all_words if word not in matched_words])

print(f"{unmatched_words}\n{matched_words}")
> and word should go in the next line
  This this
Final Thoughts:

I am by no means a regex ninja so, there may be even more clever things that can be done with just regex patterns and functions. Hopefully, this gives you some food for thought at least.

Got it:

data = ['This and this', 'word should go', 'in the next']

first_line = []
second_line = []

for item in data:
    item = item.split(' ')
    
    first_word = item[0]
    
    item.remove(first_word)
    
    others = " ".join(item)
    
    first_line.append(first_word)
    second_line.append(others)
    
print(" ".join(first_line) + "\n" + " ".join(second_line))

My Solution:

input_data = ['This and this', 'word should go ok', 'this next']

I've slightly altered your test string to better test the code.

# Example 1
# Print all words in input_data, moving any word matching the
# string "this" (match is case insensitive) to the next line.

print('Example 1')
lines = ([], [])

for words in input_data:
    for word in words.split():
      lines[word.lower() == 'this'].append(word)

result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)

The code in example 1 sorts each into the 2-element tuple, .排序到 2 元素元组The key part is the boolean expression that preforms the string comparison.

# Example 2
# Print all words in input_data, moving the second and third
# word in any string to the next line.

from itertools import count
print('\nExample 2')
lines = ([], [])

for words in input_data:
    for q in zip(count(), words.split()):
      lines[q[0] in (1, 2)].append(q[1])

result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)

The next solution is basically the same as the first. I zip each word to an integer so you know the word's position when you get to the boolean expression which, again, sorts the words into their appropriate list in .排序到适当的列表中。
As you can see, this solution is fairly flexible and can be adjusted to fit a number of scenarios.
Good luck, and I hope this helped!

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