简体   繁体   English

在Python中分隔字符串

[英]Separating a string in Python

How would I separate characters once I have a string of unseparated words? 一旦我有一串未分离的单词,我将如何分离字符?

For example to translate "take the last character of the suffix and add a space to it every time ( "aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix" ).` 例如,翻译“取后缀的最后一个字符并每次为它添加一个空格( "aSuffixbSuffixcSuffix" - > "aSuffix bSuffix cSuffix" )。

Or, more generally, to replace the x-nth character, where x is any integer (eg, to replace the 3rd, 6th, 9th, etc. character some something I choose). 或者,更一般地说,替换第x个字符,其中x是任何整数(例如,替换我选择的第3,第6,第9等字符)。

Assuming you're getting your string from this question , the easiest way is to not cram all the strings together in the first place. 假设你从这个问题中得到你的字符串,最简单的方法是不要首先把所有的字符串塞进去。 Your original create_word could be changed to this: 您的原始create_word可以更改为:

def create_word(suffix):
    letters="abcdefghijklmnopqrstuvwxyz"
    return [i + suffix for i in letters]

Then you'd be able to take e and ''.join(e) or ' '.join(e) to get the strings you want. 然后你就可以拿e''.join(e)' '.join(e)来获得你想要的字符串。

   str = "SuffixbSuffixcSuffix"

   def chunk_str(str, chunk_size):
        return [str[i:i+chunk_size] for i in range(0, len(str), chunk_size)]

   " ".join(chunk_str(str,3))

returns: 收益:

'Suf fix bSu ffi xcS uff ix'

You could use the replace method of strings. 您可以使用字符串的替换方法。 Check the documentation 查看文档

initial = "aSuffixbSuffixcSuffix"

final = initial.replace("Suffix", "Suffix ")
print(final)

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

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