peterparker
peterparker

Reputation: 51

Python: Remove First Character of each Word in String

I am trying to figure out how to remove the first character of a words in a string.

My program reads in a string.

Suppose the input is :

this is demo

My intention is to remove the first character of each word of the string, that is tid, leaving his s emo.

I have tried

  1. Using a for loop and traversing the string
  2. Checking for space in the string using isspace() function.
  3. Storing the index of the letter which is encountered after the space, i = char + 1, where char is the index of space.
  4. Then, trying to remove the empty space using str_replaced = str[i:].

But it removed the entire string except the last one.

Upvotes: 2

Views: 8755

Answers (4)

Priyavrat Mohta
Priyavrat Mohta

Reputation: 1

This method is a bit long, but easy to understand. The flag variable stores if the character is a space. If it is, the next letter must be removed

s = "alpha beta charlie"
t = ""
flag = 0
for x in range(1,len(s)):
    if(flag==0):
         t+=s[x]
    else:
        flag = 0
    if(s[x]==" "):
        flag = 1
print(t)

output
lpha eta harlie

Upvotes: 0

Aditya Kresna Permana
Aditya Kresna Permana

Reputation: 12109

You can simply using python comprehension

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

then mstr variable will contains these values 'his s emo'

Upvotes: 0

kjp
kjp

Reputation: 3116

List comprehensions is your friend. This is the most basic version, in just one line

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

output:   
his s emo

Upvotes: 5

Lev Levitsky
Lev Levitsky

Reputation: 65821

In case the input string can have not only spaces, but also newlines or tabs, I'd use 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...

Upvotes: 4

Related Questions