how do I separate a text with a list? - python

this is my code however it keeps outputting the answer as one while I want it to count the characters in the sentence.
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(",")
myList.append(newSentence)
print(myList)
for character in myList:
characterCount += 1
print (characterCount)
thank you for your help

 The one line solution
len(list("hello world")) # output 11
or...
 Quick fix to your original code
Revised code:
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
myList = list(Sentence)
print(myList)
for character in myList:
characterCount += 1
print (characterCount)
Output:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
11

You can loop over the sentence and count the characters that way:
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
for character in Sentence:
characterCount += 1
print(characterCount)

Basically you made a few mistakes: split separator should be ' ' instead of ',', no need to create a new list, and you were looping over words instead of characters.
The code should like the following:
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(" ")
for words in newSentence:
characterCount += len(words)
print (characterCount)

Related

Search list in string characters

I have to search if a word doesn't have a vowel, and then put them in another list.
I can't make it work, and I don't understand why.
for i in range(len(Cadena)):
if all Vocales[] not in Cadena:
Lista.append(Cadena[i])
Try this.
word = 'apple'
vowels = ['a','e','i','o','u','A','E','I','O','U']
for letter in word:
if letter in vowels:
#this word has a vowel, do something
else:
# this word doesn't have a vowel.
I'm not 100% sure what your variables mean, but your problem is simple.
Here is the solution:
# array with words that you to sort into two groups
words = ["abc", "def", " ggg"]
vowels = ["a", "e", " i", "o", " u"] # possibly include "y"
numVowels = len(vowels)
withVowels = [] # words with vowels
withoutVowels = [] # words without vowels
# categorize words
for w in words:
for i, v in enumerate(vowels):
if v in w:
withVowels.append(w)
elif i == (numVowels -1):
withoutVowels.append(w)
At the end of this for loop, the withVowels will contain ["abc", "def"] and withoutVowels will contain [" ggg"]
import re
def vocales(text):
#with regular expression.
print re.findall("[aeiouÁÉÍÓÚ]", text.lower(), re.IGNORECASE)
#or verifying letter by letter
print [e for e in text if e in "aeiouÁÉÍÓÚ"]
#Shows the characters that are not vowels
print [e for e in text if e not in "aeiouÁÉÍÓÚ"]
#Returns false if it has vowels
return not len([e for e in text if e in "aeiouÁÉÍÓÚ"])
vocales("Hola mundo. Hello world")
Output:
['o', 'a', 'u', 'o', 'e', 'o', 'o']
['o', 'a', 'u', 'o', 'e', 'o', 'o']
['H', 'l', ' ', 'm', 'n', 'd', '.', ' ', 'H', 'l', 'l', ' ', 'w', 'r', 'l', 'd']
False
You can set up a string with all your vowels, then you can use list comprehension to check your words against this string
vow = 'aeiou'
words = ['apple', 'banana', 'vsh', 'stmpd']
w_vowels = [i for i in words if any(k in vow for k in i)]
wo_vowels = [i for i in words if not any(k in vow for k in i)]
print(w_vowels) # => ['apple', 'banana']
print(wo_vowels) # => ['vsh', 'stmpd']
Expanded Loops without any:
w_vowels = []
for i in words:
for k in i:
if k in vow:
w_vowels.append(i)
break
wo_vowels = []
for i in words:
for k in i:
if k in vow:
break
else:
wo_vowels.append(i)

excess trailing concatenation of a string

I'm trying to write a function that will take a list and convert it to a string separated by - or a ,.
I have to use a loop for this so I came up with the following.
My problem is that I can't get rid of trailing separator. any ideas?
Output is : String is r-i-n-g-i-n-g-
should be : String is r-i-n-g-i-n-g
#A list created for the purpose of converting it to a string)
c_list = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
# Function to_string()
def to_string(my_list, sep=', '):
counter = 0
mystring = ''
for n in my_list:
n = str(n)
mystring = mystring + n
mystring = mystring + sep
return mystring
print('String is', to_string(c_list, '-'))
You can use the str.join method instead:
print('String is', '-'.join(c_list))
If you need to use a loop, however, you can make adding the separator the first thing to do in your loop instead, but make it conditional on that there is already content in mystring, so that it does not add the separator in the first iteration:
c_list = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
# Function to_string()
def to_string(my_list, sep=', '):
counter = 0
mystring = ''
for n in my_list:
if mystring:
mystring = mystring + sep
n = str(n)
mystring = mystring + n
return mystring
print('String is', to_string(c_list, '-'))
In return statement you can use string slicing to remove trailing delimiter.
return mystring[:-1]
This will remove the last character in the string.

How to print a string in alternating case?

I want to print a string in Python with alternate cases. For example my string is "Python". I want to print it like "PyThOn". How can I do this?
string = "Python"
for i in string:
if (i%2 == 0):
(string[i].upper())
else:
(string[i].lower())
print (string)
It's simply not Pythonic if you don't manage to work a zip() in there somehow:
string = 'Pythonic'
print(''.join(x + y for x, y in zip(string[0::2].upper(), string[1::2].lower())))
OUTPUT
PyThOnIc
mystring="Python"
newstring=""
odd=True
for c in mystring:
if odd:
newstring = newstring + c.upper()
else:
newstring = newstring + c.lower()
odd = not odd
print newstring
For random caps and small characters
>>> def test(x):
... return [(str(s).lower(),str(s).upper())[randint(0,1)] for s in x]
...
>>> print test("Python")
['P', 'Y', 't', 'h', 'o', 'n']
>>> print test("Python")
['P', 'y', 'T', 'h', 'O', 'n']
>>>
>>>
>>> print ''.join(test("Python"))
pYthOn
>>> print ''.join(test("Python"))
PytHon
>>> print ''.join(test("Python"))
PYTHOn
>>> print ''.join(test("Python"))
PytHOn
>>>
For Your problem code is :
st = "Python"
out = ""
for i,x in enumerate(st):
if (i%2 == 0):
out += st[i].upper()
else:
out += st[i].lower()
print out
Try it:
def upper(word, n):
word = list(word)
for i in range(0, len(word), n):
word[i] = word[i].upper()
return ''.join(word)
You can iterate using list comprehension, and force case depending on each character's being even or odd.
example:
s = "This is a test string"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss
s = "ThisIsATestStringWithoutSpaces"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss
output:
~/so_test $ python so_test.py
ThIs iS A TeSt sTrInG
ThIsIsAtEsTsTrInGwItHoUtSpAcEs
~/so_test $

Split string > list of sublists of words and characters

No imports allowed (it's a school assignment).
Wish to split a random string into a list of sublists. Words in a sublist, all other characters (including whitespace) would be in a sublist containing only one item. Anyone have some advice on how to do this;
part = "Hi! Goodmorning, I'm fine."
list = [[H,i],[!],[_],[G,o,o,d,m,o,r,n,i,n,g],[,],[_],[I],['],[m],[_],[f,i,n,e],[.]]
This does the trick:
globalList = []
letters = "abcdefghijklmnopqrstuvwxyz"
message = "Hi! Goodmorning, I'm fine."
sublist = []
for char in message:
#if the character is in the list of letters, append it to the current substring
if char.lower() in letters:
sublist.append(char)
else:
#add the previous sublist (aka word) to globalList, if it is not empty
if sublist:
globalList.append(sublist)
#adds the single non-letter character to the globalList
globalList.append([char])
#initiates a fresh new sublist
sublist = []
print(globalList)
#output is [['H', 'i'], ['!'], [' '], ['G', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g'], [','], [' '], ['I'], ["'"], ['m'], [' '], ['f', 'i', 'n', 'e'], ['.']]
Try this out :
part = "Hi! Goodmorning, I'm fine."
n = part.count(" ")
part = part.split()
k = 0
# Add spaces to the list
for i in range(1,n+1):
part.insert(i+k, "_")
k += 1
new = [] # list to return
for s in part:
new.append([letter for letter in s])
part = "Hi! Goodmorning, I'm fine."
a = []
b = []
c = 0
for i in part:
if i.isalpha():
if c == 1:
a.append(b)
b=[]
b.append(i)
c = 0
else:
b.append(i)
else:
a.append(b)
b=[]
b.append(i)
c = 1
a.append(b)
print a

Print letters not in string

I'm trying to see if a word or sentence has each letter of the alphabet and I can't get it to print all the letters that isn't in the sentence/word.
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z']
x = raw_input('')
counter = 0
counter2 = 0
for i in range(len(x))
counter += 1
for o in range(26):
counter2 += 1
if alpha[counter2] not in x[counter]:
and I'm stuck there...
alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z'}
input_chars = set(raw_input())
print alphabet - input_chars
All we do is set difference between the set of alphabet characters and the set of characters in our input. Note that the difference operation can take as a second operand any iterable, so we don't even really have to turn our input into a set if we don't want to, although this will speed up the difference a small amount. Furthermore, there is a built-in string which gives us the ascii letters so we could do it like this:
import string
print set(string.ascii_lowercase) - raw_input()
using set difference:
import string
x=raw_input()
not_found=set(string.ascii_lowercase) - set("".join(x.split()))
print (list(not_found))
output:
>>>
the quick brown fox
['a', 'd', 'g', 'j', 'm', 'l', 'p', 's', 'v', 'y', 'z']
Since you're already iterating over both strings, there is no need to use counter and counter2.
You were almost there. Python makes list operations simple, so there's no need to iterate over the lists element-by-element using indices:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sentence = raw_input('Enter a sentence: ').lower() # Because 'a' != 'A'
letters = []
for letter in sentence:
if letter in alphabet and letter not in letters:
letters.append(letter)
print(letters)
Much easier:
import string
x = raw_input()
print [c for c in string.ascii_lowercase if c not in x]

Categories

Resources