Build a long string from words in a For Loop - python

I would like to form a long sentence using a for loop in python.
I have data that came from sys.stdin and i would like to form a long sentence from the words that came from stdin.
For example,assume the words that cam from sys.stdin were
hello
to
all
developers
My current program reads as:
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
I have also tried this approach:
for k in sys.stdin:
word = ''
sentence = word + ',' + k
print(sentence)
All the above codes gives me the output;
,hello
,to
,all
,developers
But I need an output as;
hello,to,all,developers
Please Note; I NEED THE VARIABLE 'sentence' INSIDE THE LOOP BECAUSE IT WILL BE RE-USED IN THE LOOP LATER.
Any help please? Thank you for your input.

Not as familiar with for loops in python, but maybe you could try putting the "print(sentence" outside of the for loop, because print() is always going to make a new line

Try this
word = ''
for k in sys.stdin:
word = word + ',' + k
print(word)
You need to modify word, you were creating another variable each time inside the loop

sentence = ','.join(k for k in sys.stdin)

Try this
import sys
sentence = []
for k in sys.stdin:
if "\n" in k: # sys.stdin input contains newlines, remove those first
sentence.append(k[:-1]) # removes the \n (newline literal) before adding to sentence list
else:
sentence.append(k)
print(",".join(sentence)) # converts the list of words into one long string separated with commas
My approach to this contains one key step that other answers are missing, which is removing the newline "\n" from sys.stdin input.
When you try this code snippet, you'll get your output in one line.

You can use your approach
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
just add
sentence = sentence.replace('\n','')[1:]
after the loop

Related

How to capitalize the first and last letter of a string?

So it's not a very difficult problem and I've been trying to do it. Here is my sample code:
import sys
for s in sys.stdin:
s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
print(s)
This code only capitalizes the first letter and not the last letter as well. Any tips?
You are operating on lines, not words, since iterating over sys.stdin will give you strings that consist of each line of text that you input. So your logic won't be capitalizing individual words.
There is nothing wrong with your logic for capitalizing the last character of a string. The reason that you are not seeming to capitalize the end of the line is that there's an EOL character at the end of the line. The capitalization of EOL is EOL, so nothing is changed.
If you call strip() on the input line before you process it, you'll see the last character capitalized:
import sys
for s in sys.stdin:
s = s.strip()
s = s[0:1].upper() + s[1:len(s)-1] + s[len(s)-1:len(s)].upper()
print(s)
#Calculuswhiz's answer shows you how to deal with capitalizing each word in your input.
You first have to split the line of stdin, then you can operate on each word using a map function. Without splitting, the stdin is only read line by line in the for loop.
#!/usr/bin/python
import sys
def capitalize(t):
# Don't want to double print single character
if len(t) is 1:
return t.upper()
else:
return t[0].upper() + t[1:-1] + t[-1].upper()
for s in sys.stdin:
splitLine = s.split()
l = map(capitalize, splitLine)
print(' '.join(l))
Try it online!
You could just use the capitalize method for str which will do exactly what you need, and then uppercase the last letter individually, something like:
my_string = my_string.capitalize()
my_string = my_string[:-1] + my_string[-1].upper()

extracting words from a string without using the .split() function

I coded this in order to get a list full of a given string words .
data=str(input("string"))
L=[]
word=""
for i in data:
if i.isalpha() :
word+=i
elif :
L.append(word)
word=""
but, when I run this code it doesn't show the last word !
You can simply split words on a string using str.split() method, here is a demo:
data = input("string: ")
words = data.split()
L = []
for word in words:
if word.isalpha():
L.append(word)
print(L)
Note that .split() splits a string by any whitespace character by default, if you want for example to split using commas instead, you can simply use data.split(",").
You are not getting the last word into the list because it does not have non-alpha character to make it pass to the else stage and save the word to list.
Let's correct your code a little. I assume you want to check the words in the string but not characters(because what you are doing right now is checking each charackter not words.):
data=input("Input the string: ") #you don't need to cast string to string (input() returns string)
data = data+' ' # to make it save the last word
l=[] #variable names should be lowercase
word=""
for i in data:
if i.isalpha() :
word+=i
else: # you shouldn't use elif it is else if no condition is provided
l.append(word)
word=" " # not to make each word connected right after each other

How do I output the acronym on one line

I am following the hands-on python tutorials from Loyola university and for one exercise I am supposed to get a phrase from the user, capatalize the first letter of each word and print the acronym on one line.
I have figured out how to print the acronym but I can't figure out how to print all the letters on one line.
letters = []
line = input('?:')
letters.append(line)
for l in line.split():
print(l[0].upper())
Pass end='' to your print function to suppress the newline character, viz:
for l in line.split():
print(l[0].upper(), end='')
print()
Your question would be better if you shared the code you are using so far, I'm just guessing that you have saved the capital letters into a list.
You want the string method .join(), which takes a string separator before the . and then joins a list of items with that string separator between them. For an acronym you'd want empty quotes
e.g.
l = ['A','A','R','P']
acronym = ''.join(l)
print(acronym)
You could make a string variable at the beginning string = "".
Then instead of doing print(l[0].upper()) just append to the string string += #yourstuff
Lastly, print(string)

I need to make the output be in one line

So, I already have the code to get all the words with digits in them out of the text, now all I need to do is to have the text all in one line.
with open("lolpa.txt") as f:
for word in f.readline().split():
digits = [c for c in word if c.isdigit()]
if not digits:
print(word)
The split makes the words all be in a different column.
If I take out the .split(), it types in the words without the digits, literally just takes the digits out of the words, and makes every letter to be in a different column.
EDIT: Yes, print(word,end=" ") works, thanks. But I also want the script to now read only one line. It can't read anything that is on line 2 or 3 etc.
The second problem is that the script reads only the FIRST line. So if the input in the first line would be
i li4ke l0ke like p0tatoes potatoes
300 bla-bla-bla 00bla-bla-0211
the output would be
i like potatoes
In Python v 3.x you'd use
print(word, end='')
to avoid the newline.
in Python v 2.x
print word,
you'd use the comma at the end of the items you are printing. Note that unlike in v3 you'd get a single blank space between consecutive prints
Note that print(word), won't prevent a newline in v 3.x.
--
Update based on edit in original post re code problem:
With input:
i li4ke l0ke like p0tatoes potatoes
300 bla-bla-bla 00bla-bla-0211
this code:
def hasDigit(w):
for c in w:
if c.isdigit():
return True
return False
with open("data.txt") as f:
for line in f:
digits = [w for w in line.split() if not hasDigit(w)]
if digits:
print ' '.join(digits)
#   break  # uncomment the "break" if you ONLY want to process the first line 
will yield all the "words" that do not contain digits:
i like potatoes
bla-bla-bla <-- this line won't show if the "break" is uncommented above
Note:
The post was a bit unclear if you wanted to process only the first line of the file, or if the problem was that your script only processed the first line. This solution can work either way depending on whether the break statement is commented out or not.
with open("lolpa.txt") as f:
for word in f.readline().split():
digits = [c for c in word if c.isdigit()]
if not digits:
print word,
print
Not , at the end of print.
If you're using python 3.x, you can do:
print (word,end="")
to suppress the newline -- python 2.x uses the somewhat strange syntax:
print word, #trailing comma
Alternatively, use sys.stdout.write(str(word)). (this works for both python 2.x and 3.x).
you can use join():
with open("lolpa.txt") as f:
print ' '.join(str(x.split()) for x in f if not [c for c in x.split() if c.isdigit()])
using a simple for loop:
import sys
with open("data.txt") as f:
for x in f: #loop over f not f.readline()
word=x.split()
digits = [c for c in word if c.isdigit()]
if not digits:
sys.stdout.write(str(word)) #from mgilson's solution

Replacing each match with a different word

I have a regular expression like this:
findthe = re.compile(r" the ")
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"
What I am trying to do is to replace each occurrence with an associated replacement word from a list so that the end sentence would look like this:
>>> print sentence
This is firstthe first sentence in secondthe whole universe
I tried using re.sub inside a for loop enumerating over replacement but it looks like re.sub returns all occurrences. Can someone tell me how to do this efficiently?
If it is not required to use regEx than you can try to use the following code:
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"
words = sentence.split()
counter = 0
for i,word in enumerate(words):
if word == 'the':
words[i] = replacement[counter]
counter += 1
sentence = ' '.join(words)
Or something like this will work too:
import re
findthe = re.compile(r"\b(the)\b")
print re.sub(findthe, replacement[1],re.sub(findthe, replacement[0],sentence, 1), 1)
And at least:
re.sub(findthe, lambda matchObj: replacement.pop(0),sentence)
Artsiom's last answer is destructive of replacement variable. Here's a way to do it without emptying replacement
re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence)
You can use a callback function as the replace parameter, see how at:
http://docs.python.org/library/re.html#re.sub
Then use some counter and replace depending on the counter value.

Categories

Resources