Python String Handling Functions - python

Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
I have to create a program where I need to ask a user for a string and then my program must print the length of the string, the number of letters, the number of digits and the number of characters that are not letters.
counter = 0
num = 0
extra = 0
wrd = raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter + 1
print "You have " + str(counter) +" letters in your sentence."
for n in wrd:
if n.isnumeric():
num = num + 1
print "You have " + str(num) + " number(s) in your sentence"
for l in wrd:
extra = extra + 1
print "You have " + str(extra) + " characters that are not letters or numbers."
I got the first two parts figured out albeit I'm stuck on the last...I know its easier to just create one while loop but since I already started, I want to stick with three four loops.

You don't need another function. Since you've already counted the other characters, subtract them from the total:
print "You have", len(wrd) - counter - num, "characters that are not letters or numbers."

Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
No, but its pretty easy to create your own:
import string
def has_special_chars(s):
return any(c in s for c in string.punctuation)
Test:
>>> has_special_chars("ab#tjhjf$dujhf&")
True
>>> has_special_chars("abtjhjfdujhf")
False
>>>
In your case, you would use it like:
for l in wrd:
if has_special_chars(l)
extra=extra+1
But as #TigerHawkT3 has already beat me to saying, you should simply use len(wrd) - counter - num instead. Its the most canonical and obvious way.

Just to log a generic answer that will apply beyond this context -
import string
def num_special_char(word):
count=0
for i in word:
if i in string.punctuation:
count+=1
return count
print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers."
Output
You have 2 characters that are not letters or numbers.

Use one for loop with if, elif and else:
sentence = raw_input("Please enter a short sentence.")
alpha = num = extra = 0
for character in sentence:
if character.isspace():
pass
elif character.isalpha():
alpha += 1
elif character.isnumeric():
num += 1
else:
extra += 1
print "You have {} letters in your sentence.".format(alpha)
print "You have {} number(s) in your sentence".format(num)
print "You have {} characters that are not letters or numbers.".format(extra)

Related

how to extract a sentence from string in python using simple for loop?

str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")

How do I have a list accept lowercase in place of capitalized letters in Hangman for a randomized list in Python 3?

I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.
import random
import urllib.request
wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()
###########
# Methods #
###########
def Run():
dashes1 = "-" * len(word)
dashes2 = "-" * len(word2)
used_letter = []
dashes = dashes1 + " " + dashes2
#dashes ="-" * len(secretWord)
guessesLeft = 6
while guessesLeft > -1 and not dashes == secretWord:
print(used_letter)
print(dashes)
print (str(guessesLeft))
guess = input("Guess:")
used_letter.append(guess)
if len(guess) != 1:
print ("Your guess must have exactly one character!")
elif guess in secretWord:
print ("That letter is in the secret word!")
dashes = updateDashes(secretWord, dashes, guess)
else:
print ("That letter is not in the secret word!")
guessesLeft -= 1
if guessesLeft < 0:
print ("You lose. The word was: " + str(secretWord))
print(dashes)
else:
print ("Congrats! You win! The word was: " + str(secretWord))
print(dashes)
def updateDashes(secret, cur_dash, rec_guess):
result = ""
for i in range(len(secret)):
if secret[i] == rec_guess:
result = result + rec_guess
else:
result = result + cur_dash[i]
return result
########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one
word or add more above to create and combine more words will have to adjust
abouve in Run()
splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])
print (splitw)
Run()
any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.
you could compare after you converted everything to lowercase.
e.g. you could do
secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase
for the input you should do the same:
guess = input("Guess:").lower()
after that it should not matter if it is upper or lower case. it should always match if the letter is the correct one.
hope that helps
Simply check everything in lowercase:
[...]
elif guess.lower() in secretWord.lower():
[...]
and so on.
I would just change this line:
while guessesLeft > -1 and not dashes == secretWord:
to:
while guessesLeft > -1 and not dashes.lower() == secretWord.lower():
This way you are always comparing lower-case representations of the user's input to the lower-case representation of your secretWord. Since this is the main loop for your game, you want to break out of this as soon as the user's guess matches your word regardless of case. Then later in your code, you will still check whether they had any guesses left, and print out their answer and the secret word as before.
No other changes required, I think.
You could just force all comparisons to be made in the same Case, such as lowercase.
Let’s say that your word is "Bacon". and someone enters "o".
That will be a match because quite obviously “o” equals “o” so you can cross that letter off the list of letters left to guess.
But in the case that someone enters “b” then b is NOT equal to “B”.
So why not just force all letters to be compared using the same case?
So your comparison will be like
elif guess.Lower() in secretWord.Lower()
My python is rusty as hell, but the idea here should do what you want to do

Function that give the number of words

I'm doing a function that give the number of words in a sentence.
Example: " Hello L World " there are 3 "words" (A letter is counted like a word).
Here is my code:
def number_of_word(s):
"""
str -> int
"""
# i : int
i = 0
# nb_word : int
nb_word = 0
if s == "":
return 0
else:
while i < len(s)-1:
if ((s[i] != " ") and (s[i+1] == " ")):
nb_word = nb_word + 1
i = i + 1
else:
i = i + 1
if s[len(s)-1] != " ":
nb_word = nb_word + 1
return nb_word
else:
return nb_word
I tried my function and I think it works. But, I also think there is a better way to do a function that do the same thing in an easier way.
Can you tell me if you know one better function? Or any comments on mine?
I hade to use:
if s == "":
return 0
else:
...........
because if I didn't, my function didn't work for number_of_word("")
If you define words as character sequences separated by one or more whitespaces, then you can simply use the split method of strings to split to words,
and then len to get their count:
def number_of_word(s):
return len(s.split())
From the documentation (emphasis mine):
split(...) method of builtins.str instance
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done. If sep is not
specified or is None, any whitespace string is a separator and empty
strings are removed from the result.
If you want you can use RegExp
import re
def number_of_word(s):
pattern = r'\b\w+\b'
return len(re.findall(pattern, s))
If you can't use split or regex, I think this is the right solution:
def count(sentence):
wlist = []
word = ""
for c in sentence:
if c == " ":
wlist.append(word)
word = ""
else:
word += c
wlist.append(word)
return len(wlist)
You can use split() method :
def count(string1):
string1=string1.split()
return len(string1)
print(count(" Hello L World "))
output:
3
I can't use more python' functions than just "len".
So, I can't use split or RegExp.
So I want to make this function with just basic code and len.
Well, since the requirements were published, here's a way to do this without calling any library functions:
def count_words(sentence):
count, white = 0, True
for character in sentence:
if character not in " \t\n\r":
if white:
count += 1
white = False
else:
white = True
return count

How can I capitalize a character with an odd-numbered index in a string?

So I was doing our exercise when I came across capitalizing characters in odd indices. I tried this:
for i in word:
if i % 2 != 0:
word[i] = word[i].capitalize()
else:
word[i] = word[i]
However, it ends up showing an error saying that not all strings can be converted. Can you help me debug this code snippet?
The problem is strings in python are immutable and you cannot change individual characters. Apart fro that when you iterate through a string you iterate over the characters and not the indices. So you need to use a different approach
A work around is
(using enumerate)
for i,v in enumerate(word):
if i % 2 != 0:
word2+= v.upper()
# Can be word2+=v.capitalize() in your case
# only as your text is only one character long.
else:
word2+= v
Using lists
wordlist = list(word)
for i,v in enumerate(wordlist):
if i % 2 != 0:
wordlist[i]= v.upper()
# Can be wordlist[i]=v.capitalize() in your case
# only as your text is only one character long.
word2 = "".join(wordlist)
A short note on capitalize and upper.
From the docs capitalize
Return a copy of the string with its first character capitalized and the rest lowercased.
So you need to use upper instead.
Return a copy of the string with all the cased characters converted to uppercase.
But in your case both work accurately. Or as Padraic puts it across "there is pretty much no difference in this example efficiency or output wise"
You need enumerate and capitalise any character at any odd i where i is the index of each char in the word:
word = "foobar"
print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR
ch.upper() if i % 2 else ch is a conditional expression where we change the char if the condition is True or else leave as is.
You cannot i % 2 when i is the actual character from the string, you would need to use range in your code or use enumerate and concatenate the changed characters to an output string or make words a list.
Using a list you can use assignment:
word = "foobar"
word = list(word)
for i, ele in enumerate(word):
if i % 2:
word[i] = ele.upper()
print("".join(word))
Using an output string:
word = "foobar"
out = ""
for i, ele in enumerate(word):
if i % 2:
out += ele.upper()
else:
out += ele
if i % 2: is the same as writing if i % 2 != 0.
This is how I would change word letters in a word or a sentence to uppercase
word = "tester"
letter_count = 1
new_word = []
for ch in word:
if not letter_count % 2 == 0:
new_word.append(ch.upper())
else:
new_word.append(ch)
letter_count += 1
print "".join(new_word)
if I wanted to change odd words in a sentence to uppercase I would do this
sentence = "this is a how we change odd words to uppercase"
sentence_count = 1
new_sentence = []
for word in sentence.split():
if not sentence_count % 2 == 0:
new_sentence.append(word.title() + " ")
else:
new_sentence.append(word + " ")
sentence_count += 1
print "".join(new_sentence)
I think it will help...
s = input("enter a string : ")
for i in range(0,len(s)):
if(i%2!=0):
s = s.replace(s[i],s[i].upper())
print(s)

Testing string against a set of vowels - Python

This is a module in my program:
def runVowels():
# explains what this program does
print "This program will count how many vowels and consonants are"
print "in a string."
# get the string to be analyzed from user
stringToCount = input("Please enter a string: ")
# convert string to all lowercase letters
stringToCount.lower()
# sets the index count to it's first number
index = 0
# a set of lowercase vowels each element will be tested against
vowelSet = set(['a','e','i','o','u'])
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
# sets the loop to run as many times as there are characters
# in the string
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
# prints results
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
# runs the main menu again
getSelection()
However, when I test this program, I get this error:
line 28, in runVowels
stringToCount = input("Please enter a string: ")
File "<string>", line 1
PupEman dABest
^
SyntaxError: unexpected EOF while parsing
I tried adding a + 1 to the "while index < len(stringToCount)" but that didn't help either. I'm pretty new to python and I don't really understand what's wrong with my code. Any help would be appreciated.
I researched this error, all I found out was that EOF stands for end of file. This didn't help at all with resolving my problem. Also, I understand that sometimes the error isn't necessarily where python says the error is, so I double-checked my code and nothing seemed wrong in my eyes. Am I doing this the round-about way by creating a set to test the string elements against? Is there a simpler way to test if string elements are in a set?
Question resolved. Thank you to all!
Looks like you're using Python 2. Use raw_input(...) instead of input(...). The input() function will evaluate what you have typed as a Python expression, which is the reason you've got a SyntaxError.
As suggested use raw_input. Also you don't need to do this:
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
Strings in Python are iterable, so you can just do something like this:
for character in stringToCount:
if character in vowelSet : # Careful with variable names, one is a list and one an integer, same for consonants.
vowels += 1
elif character in consonantsSet: # Need this, if something is not in vowels it could be a number.
consonants += 1
else:
print "Your entry should only include letters."
This should do just fine. Using a while is not necessary here, and very non-Pythonic imho. Use the advantage of using a nice language like Python when you can to make your life easier ;)
You can count the vowels like so:
>>> st='Testing string against a set of vowels - Python'
>>> sum(1 for c in st if c.lower() in 'aeiou')
12
You can do something similar for consonants:
>>> sum(1 for c in st if c.lower() in 'bcdfghjklmnpqrstvwxyz')
26
Also,
if stringToCount[index] in vowels:
should read
if stringToCount[index] in vowelSet:
Here's another way you could solve the same thing:
def count_vowels_consonants(s):
return (sum(1 for c in s if c.lower() in "aeiou"),
sum(1 for c in s if c.lower() in "bcdfghjklmnpqrstvwxyz"))
To wit:
>>> count_vowels_consonants("aeiou aeiou yyy")
(10, 3)
>>> count_vowels_consonants("hello there")
(4, 6)
Python truly is grand.
The errors in your file run as follows (plus some suggestions):
stringToCount = input("Please enter a string: ")
This should be raw_input if you want what the user typed in as a string.
stringToCount.lower()
The .lower() method returns a new string with its letters lowered. It doesn't modify the original:
>>> a = "HELLO"
>>> a.lower()
"hello"
>>> a
"HELLO"
vowelSet = set(['a','e','i','o','u'])
Here you could just as easily do:
vowelSet = set("aeiou")
Note you also don't strictly need a set but it is indeed more efficient in general.
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
Please, you don't need comments for such simple statements.
index = 0
while index < len(stringToCount):
You usually don't need to use a while loop like this in python. Note that all you use index for is to get the corresponding character in stringToCount. Should instead be:
for c in stringToCount:
Now instead of:
if stringToCount[index] in vowels:
vowels += 1
index += 1
You just do:
if c in vowels:
vowels += 1
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
Not quite right. You're checking that a character doesn't equal a set. Maybe you meant:
elif c not in vowels:
consonants += 1
But then there'd be no else case... Got to fix your logic here.
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
The above is more pythonically written as:
print "In your string, there are: %s vowels %s consonants" % (
vowels, consonants)
# runs the main menu again
getSelection()
Not sure why you're calling that there - why not call getSelection() from whatever calls runVowel()?
Hope that helped! Enjoy learning this great language.
Bah, all that code is so slow ;). Clearly the fastest solution is:
slen = len(StringToCount)
vowels = slen - len(StringToCount.translate(None, 'aeiou'))
consonants = slen - vowels
...note that I don't claim it's the clearest... just the fastest :)

Categories