Python标记化字符串

Python标记化字符串,python,regex,tokenize,Python,Regex,Tokenize,我是python新手,想知道如何根据指定的分隔符标记字符串。 例如,如果我有字符串“brother's”,我想将其转换为[“brother”、“\s”]或字符串“red/blue”转换为[“red”、“blue”],那么最合适的方法是什么?谢谢。您要查找的是调用,它在str对象上被调用。例如: >>> brotherstring = "brother's" >>> brotherstring.split("'") ['brother', 's'] >&g

我是python新手,想知道如何根据指定的分隔符标记字符串。
例如,如果我有字符串“brother's”,我想将其转换为[“brother”、“\s”]或字符串“red/blue”转换为[“red”、“blue”],那么最合适的方法是什么?谢谢。

您要查找的是调用,它在
str
对象上被调用。例如:

>>> brotherstring = "brother's"
>>> brotherstring.split("'")
['brother', 's']
>>> redbluestring = "red/blue"
>>> redbluestring.split("/")
['red', 'blue']
split
上有一些变体,例如
rsplit
分区
,等等,它们都做不同的事情。阅读文档以找到最适合您的方法。

您可以使用以下方法:

试试这个

>>> strr =  "brother's"
>>> strr.replace("'","\\'").split("\\")
['brother', "'s"]

>>> strrr = "red/blue"
>>> strrr.split('/')
['red', 'blue']

我将从
pydoc str
开始工作。谢谢。如果我有像“兄弟”这样的词,在“兄弟”后面加上一个引号,我希望它是['brother','\'s'],怎么样?这是一个很好的答案。它显示了在标点符号不是分隔符的情况下如何保留标点符号。如果撇号真的不需要的话,你可以在以后重建原作,或者进一步清理。@VISQL谢谢你的欣赏。
>>> strr =  "brother's"
>>> strr.replace("'","\\'").split("\\")
['brother', "'s"]

>>> strrr = "red/blue"
>>> strrr.split('/')
['red', 'blue']