Python:删除字符串中每个单词的第一个字符

时间:2012-06-19 06:30:33

标签: python python-2.7

我试图找出如何删除字符串中单词的第一个字符。

我的程序读入一个字符串。

假设输入为:

  

这是演示

我的目的是删除字符串中每个单词的第一个字符,即 tid,离开his s emo

我试过了

  1. 使用for loop并遍历字符串
  2. 使用isspace() function.
  3. 检查字符串中的空格
  4. 存储之后遇到的字母索引 space,i = char + 1,其中char是空间索引。
  5. 然后,尝试使用str_replaced = str[i:].
  6. 删除空白区域

    但除了最后一个字符串外,它删除了整个字符串。

4 个答案:

答案 0 :(得分:5)

列表理解是你的朋友。这是最基本的版本,只需一行

str = "this is demo";
print " ".join([x[1:] for x in str.split(" ")]);

output:   
his s emo

答案 1 :(得分:4)

如果输入字符串不仅包含空格,还包含换行符或制表符,我会使用regex

In [1]: inp = '''Suppose we have a
   ...: multiline input...'''

In [2]: import re

In [3]: print re.sub(r'(?<=\b)\w', '', inp)
uppose e ave 
ultiline nput...

答案 2 :(得分:0)

尝试(python 3.2)

import os

s = '''this is a test of the... What? What is going on now?
You guys are cu-rayzy!
Morons!'''

new_lines = []
lines=s.strip().split("\n")
for line in lines:
    new_words = []
    for word in line.strip().split(" "):
        new_words.append(word[1:])
    new_lines.append(' '.join(new_words))
new_statement = "\n".join(new_lines)

print (s)

print (new_statement)

这会处理新行,但不保留空格,并从每行的前端和末尾删除空格。

答案 3 :(得分:0)

你可以简单地使用python comprehension

str = 'this is demo'
mstr = ' '.join([s[1:] for s in str.split(' ')])

然后mstr变量将包含这些值'his s emo'

相关问题