简体   繁体   中英

How to add space before a particular string in python

I have the following output after removing all spaces from a string

テレビを付けて

テレビつけて

つけて

テレビをオンにして

However, I'm trying to add a space either after the を character, or before つけて after テレビ

The desired output is as follows

テレビを 付けて

テレビ つけて

つけて

テレビを オンにして

I've tried to use some def function but not sure how to finish it off, or even if it'll work.

def teform(txt):

    if x = "オンにして":
        return " して"
    elif y = "つけて":
        return " つけて"
    elif z = "付けて":
        return " 付けて"
    else: 
        return  # ...(not sure what goes here)

You cannot use = to compare items, you must use == .

Apart from the wrong comparing syntax, it seems you don't really know how to approach this – you don't need a loop of any kind. Just use txt.replace to target and change those specific substrings:

def teform(txt):
    # add a space after を
    txt = txt.replace ('を','を ')
    # add a space between テレビ and つけて
    txt = txt.replace ('テレビつけて', 'テレビ つけて')
    return txt

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