簡體   English   中英

Python:刪除字符串中每個單詞的第一個字符

[英]Python: Remove First Character of each Word in String

我試圖找出如何刪除字符串中的單詞的第一個字符。

我的程序讀入一個字符串。

假設輸入是:

這是演示

我的目的是刪除字符串中每個單詞的第一個字符,即tid ,留下his s emo

我努力了

  1. 使用for loop並遍歷字符串
  2. 使用isspace() function.檢查字符串中的空間 isspace() function.
  3. 存儲空格后遇到的字母索引, i = char + 1,其中char是空格索引。
  4. 然后,嘗試使用str_replaced = str[i:].刪除空白區域str_replaced = str[i:].

但它刪除了除最后一個之外的整個字符串。

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

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

output:   
his s emo

如果輸入字符串不僅可以包含空格,還可以包含換行符或制表符,我會使用正則表達式

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...

試試(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)

這會處理新行,但不會保留空格,並從每行的前端和末尾剝離空格。

你可以簡單地使用python理解

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

然后mstr變量將包含這些值'his s emo'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM