简体   繁体   中英

replace 4th space with \n in Python

my problem is that im working with PIL. I need to make it on multiple lines the text, to make sure it wont go off the image. my idea is that it would replace every fourth space with \n something like replace(' '[4], '\n') . does anything like that exists?

You can create a while loop with input.find to find the nth occurrence and if it exists, replace the string on the found position.

def replaceOnNthPos(input, matchStr, repStr, nth):
    findPos = input.find(matchStr)
    index = findPos != -1
    while findPos != -1 and index != nth:
        findPos = input.find(matchStr, findPos + 1)
        index += 1
    if index == nth:
        return input[:findPos] + repStr + input[findPos + len(matchStr):]
    return input
    
input = "Hello World Hello World Hello World Hello World"
print(replaceOnNthPos(input, " ", "\n", 4))

If i'm understand what you need, a simple call to the 'replace' method of string should suffice.

four_space_string = "    i'm save"
four_space_string.replace("    ", "\n")

>>>"\ni'm save"

try this one liner without regex:

text = "hi i am here your original text block nice yo meet you!"
text = ''.join([line + ' ' if not i %4 == 0 else line +'\n' for i,line in enumerate(text.split(' '))])
print(text)
>>>>
  hi i am here
  your original text block    
  nice yo meet you!

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