希望在python中解析字符串

2024-03-28 14:01:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一系列我正在使用的python字符串,它们的形式总是

initialword_content

我想去掉initialword部分,它总是相同数量的字符,然后我想把_的所有实例都变成空格--因为content可能有一些下划线--最简单的方法是什么?你知道吗


Tags: 实例方法字符串数量content字符形式空格
3条回答

首先,将字符串拆分一次(使用参数1到split),得到两个部分:丢弃的'initialword'和其余部分,用空格替换所有下划线。你知道吗

s = 'initialword_content' 
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content'

s = 'initialword_content_with_more_words' 
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content with more words'

这可以通过一个命令完成:

s.split('_', 1)[1].replace('_', ' ')

另一种方式:

' '.join(s.split('_')[1:])

或者,如果“initialword”的长度总是相同的(而且你不必每次都计算),那么就采用@JunHu的解决方案。你知道吗

我使用了切片和replace()函数。replace()简单。。。替换!你知道吗

string = 'initialword_content'
content = string[12:] # You mentioned that intialword will always be the same length, so I used slicing.
content = content.replace('_', ' ')

例如:

>>> string = 'elephantone_con_ten_t' # elephantone was the first thing I thought of xD
>>> content = string[12:]
>>> content
... con_ten_t
>>> content = content.replace('_', ' ')
>>> content
... con ten t

但是,如果您还想在其他地方引用“elephantone”,请执行以下操作:

>>> string = 'elephantone_con_ten_t'
>>> l = string.split('_', 1) # This will only strip the string ONCE from the left.
>>> l[0]
... 'elephantone'
>>> l[1].replace('_', ' ')
... 'con ten t'
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs

由于initialword总是有相同的字符数,所以您可以只得到字符串的后缀。使用字符串.替换将所有“\”替换为空格。你知道吗

相关问题 更多 >