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'
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'
首先,将字符串拆分一次(使用参数1到
split
),得到两个部分:丢弃的'initialword'和其余部分,用空格替换所有下划线。你知道吗这可以通过一个命令完成:
另一种方式:
或者,如果“initialword”的长度总是相同的(而且你不必每次都计算),那么就采用@JunHu的解决方案。你知道吗
我使用了切片和replace()函数。replace()简单。。。替换!你知道吗
例如:
但是,如果您还想在其他地方引用“elephantone”,请执行以下操作:
由于initialword总是有相同的字符数,所以您可以只得到字符串的后缀。使用字符串.替换将所有“\”替换为空格。你知道吗
相关问题 更多 >
编程相关推荐