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

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

Related

making first letter of input uppercase with split in python

I got most of the code down but I am having issues getting the string to space back out after making the first letter of each word uppercase
here's what I have so far:
message = input('Write a short message.')
new_message = message.split()
glue = ""
for item in new_message:
glue += item[0].upper() + item[1:]
print(glue)
try with:
message.capitalize()
If you want to capitalize each word you can try capitalize() and the code will look like this:
message = input('Write a short message.')
new_message = message.split()
cap_message = [x.capitalize() for x in new_message]
print(cap_message)
message.split() - split the string into a list using default separator which is any whitespace. The result is a list of words.
capitalize each word in the list using List Comprehention. The list of capitalized words is saved in cap_message variable for code clarity.
print the list of capitalized words

Why my function doesn't return a new string?

My assignment was to write a function with one string parameter that returns a string. The function should extract the words within this string, drop empty words as well as words that are equal to "end" and "exit", convert the
remaining words to upper case, join them with the joining token string ";" and return this
newly joined string.
This is my function but if the string doesnt contain the words "exit" or "end" no new string is returned:
def fun(long_string):
stop_words = ('end', 'exit', ' ')
new_line = ''
for word in long_string:
if word in stop_words:
new_line = long_string.replace(stop_words, " ")
result = ';'.join(new_line.upper())
return result
print(fun("this is a long string"))
The condition of if is never True, since word is not a real "word"; word in your code will be each "character" of long_string. So what if really does here is comparing 't' with 'end' and so on. Therefore, new_line always remains to be the empty string as initialized.
You will need split to work with words:
def fun(long_string):
return ';'.join(word for word in long_string.split() if word not in ('end', 'exit'))
print(fun("this is a long string")) # this;is;a;long;string
You don't need to check for empty words, because split considers them as separators (i.e., not even a word).
for word in long_string will iterate over each character in long_string, not each word. The next line compares each character to the words in stop_words.
You probably want something like for word in long.string.split(' ') in order to iterate over the words.

(python) I keep getting an IndexError: string index out of range

I am trying to solve the question
Implement the ​mapper​, ​mapFileToCount​, which takes a string (text from a file) and returns the number of capitalized words in that string. A word is defined as a series
of characters separated from other words by either a space or a newline. A word is capitalized if its first letter is capitalized (A vs a).
and my python code currently reads
def mapFileToCount(s):
lines = (str(s)).splitlines()
words = (str(lines)).split(" ")
up = 0
for word in words:
if word[0].isupper() == True:
up = up + 1
return up
However I keep getting the error IndexError: string index out of range
please help
For now
given Hi huy \n hi you there
lines will be ['Hi huy ', ' hi you there']
words will be ["['Hi", 'huy', "',", "'", 'hi', 'you', "there']"] as you use the str(lines) to split on
I'd suggest you split on any whitespace at once with words = re.split("\s+", s).
Then the problem of IndexError comes in cases like Hi where are you__ (_ is space), when you split there will be an empty string at the end, and you can't access the first char char of this, so just add a condition in the if
if word because 0-size word are False, and other True
if word[0].isupper() for you test
import re
def mapFileToCount(s):
words = re.split("\s+", s)
up = 0
for word in words:
if word and word[0].isupper():
up = up + 1
return up
The string index out of range means that the index you are trying to access does not exist in a string. That means you're trying to get a character from the string at a given point. If that given point does not exist , then you will be trying to get a character that is not inside of the string.
In your code its that word[0].

Convert titlecase words in the string to lowercase words

I want to convert all the titlecase words (words starting with uppercase character and having rest of the characters as lowercase) in the string to the lowercase characters. For example, if my initial string is:
text = " ALL people ARE Great"
I want my resultant string to be:
"ALL people ARE great"
I tried the following but it did not work
text = text.split()
for i in text:
if i in [word for word in a if not word.islower() and not word.isupper()]:
text[i]= text[i].lower()
I also checked related question Check if string is upper, lower, or mixed case in Python.. I want to iterate over my dataframe and for each word that meet this criteria.
You could define your transform function
def transform(s):
if len(s) == 1 and s.isupper():
return s.lower()
if s[0].isupper() and s[1:].islower():
return s.lower()
return s
text = " ALL people ARE Great"
final_text = " ".join([transform(word) for word in text.split()])
You can use str.istitle() to check whether your word represents the titlecased string, i.e. whether first character of the word is uppercase and rest are lowercase.
For getting your desired result, you need to:
Convert your string to list of words using str.split()
Do the transformation you need using str.istitle() and str.lower() (I am using list comprehension for iterating the list and for generating a new list of words in desired format)
Join back the list to strings using str.join() as:
For example:
>>> text = " ALL people ARE Great"
>>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
'ALL people ARE great'

How might I create an acronym by splitting a string at the spaces, taking the character indexed at 0, joining it together, and capitalizing it?

My code
beginning = input("What would you like to acronymize? : ")
second = beginning.upper()
third = second.split()
fourth = "".join(third[0])
print(fourth)
I can't seem to figure out what I'm missing. The code is supposed to the the phrase the user inputs, put it all in caps, split it into words, join the first character of each word together, and print it. I feel like there should be a loop somewhere, but I'm not entirely sure if that's right or where to put it.
Say input is "Federal Bureau of Agencies"
Typing third[0] gives you the first element of the split, which is "Federal". You want the first element of each element in the sprit. Use a generator comprehension or list comprehension to apply [0] to each item in the list:
val = input("What would you like to acronymize? ")
print("".join(word[0] for word in val.upper().split()))
In Python, it would not be idiomatic to use an explicit loop here. Generator comprehensions are shorter and easier to read, and do not require the use of an explicit accumulator variable.
When you run the code third[0], Python will index the variable third and give you the first part of it.
The results of .split() are a list of strings. Thus, third[0] is a single string, the first word (all capitalized).
You need some sort of loop to get the first letter of each word, or else you could do something with regular expressions. I'd suggest the loop.
Try this:
fourth = "".join(word[0] for word in third)
There is a little for loop inside the call to .join(). Python calls this a "generator expression". The variable word will be set to each word from third, in turn, and then word[0] gets you the char you want.
works for me this way:
>>> a = "What would you like to acronymize?"
>>> a.split()
['What', 'would', 'you', 'like', 'to', 'acronymize?']
>>> ''.join([i[0] for i in a.split()]).upper()
'WWYLTA'
>>>
One intuitive approach would be:
get the sentence using input (or raw_input in python 2)
split the sentence into a list of words
get the first letter of each word
join the letters with a space string
Here is the code:
sentence = raw_input('What would you like to acronymize?: ')
words = sentence.split() #split the sentece into words
just_first_letters = [] #a list containing just the first letter of each word
#traverse the list of words, adding the first letter of
#each word into just_first_letters
for word in words:
just_first_letters.append(word[0])
result = " ".join(just_first_letters) #join the list of first letters
print result
#acronym2.py
#illustrating how to design an acronymn
import string
def main():
sent=raw_input("Enter the sentence: ")#take input sentence with spaces
for i in string.split(string.capwords(sent)):#split the string so each word
#becomes
#a string
print string.join(i[0]), #loop through the split
#string(s) and
#concatenate the first letter
#of each of the
#split string to get your
#acronym
main()
name = input("Enter uppercase with lowercase name")
print(f'the original string = ' + name)
def uppercase(name):
res = [char for char in name if char.isupper()]
print("The uppercase characters in string are : " + "".join(res))
uppercase(name)

Categories

Resources