简体   繁体   English

如何在python中的特定字符串之前添加空间

[英]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函数,但不确定如何完成它,即使它能正常工作。

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: 只需使用txt.replace定位并更改那些特定的子字符串即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM