I have a string in Python like this:
a = "one house"
For my program I need to convert that one into a literal 1, which I use the word2number library for in Python.
Except, when I convert it, I get this.
a = "one house"
a = w2n.word_to_num(a)
print(a)
>> 1
I want to retain the "house" and make the string like this:
>> "1 house"
With no prior information about the position of the number:
a = 'One house in the middle of three woods'
s = a.split()
o = []
for word in s:
try:
o += [str(w2n.word_to_number(word))]
except ValueError:
o += [word]
print(' '.join(o))
output:: '1 house in the middle of 3 woods'
It appears that the word2number module returns an integer, this means that the house part cannot be retained as it is a string. If you know that the number is always going to be the first word, you could try:
a = "one house"
a_list = a.split(' ')
a_list[0] = str(w2n.word_to_num(a_list[0]))
print(' '.join(a_list))
Whereby you split the string into multiple strings in a list, run the word_to_num function on the first string and then recreate the string using .join()
Related
I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code?
names = input("Enter list of names: ")
name = names.split(" ")
num = len(name)
ab = ""
print("Number of words:", num)
for i in range(num):
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
a_b = ab.split(' ')
print("Number of words that end with a or b: ",len(a_b))
In Python boolean (True and False) are the same as the integers 1 and 0. This means you can use sum() to count True booleans. str.endswith() returns a boolean. This means you can just do this:
words = ["stab", "drama", "hello", "magma", "test"]
a_b = sum(word.endswith(('a', 'b')) for word in words)
# 3
z_c = sum(word.endswith(('z', 'c')) for word in words)
# 0
Any tips on how to correct this code?
Others have answered alternative, working solutions, but I want to try to point out the specific things wrong in your code snippet and tips to correct.
First here's a copy of your snippet with some simple debugging prints along with their output (running in python 3.10).
names = "Barry Lima Bab"
name = names.split(" ")
print(f"{name=}") # name=['Barry', 'Lima', 'Bab']
num = len(name)
print(f"{num=}") # num=3
ab = ""
print("Number of words:", num)
for i in range(num):
print(name[i]) # Barry -> Lima -> Bab
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
print(f"{ab=}") # ab=''
a_b = ab.split(' ')
print(f"{a_b=}") # a_b=['']
Breaking things down step by step like this is a great starting point for better understanding what's going on.
if name[i] == ' ': Notice the value of name[i] so this check never resolves to True meaning the code inside never runs
if the inner code did run, you'd hit a NameError: name 'a' is not defined. Did you mean: 'ab'? because a is undefined. Probably meant 'a' here. same for b
In my example, name[i-1] would be 'Bab' -> 'Barry' -> 'Lima' which is probably not what you're expecting. This is because you're getting the -1th, 0th, 1st items in name. to get the last letter from the name, you want name[i][-1] here
if you then get into either of the furthest inside conditions, you'd encounter AttributeError: 'str' object has no attribute 'append' which happens because append is for list not str. You couldchange ab to be a list to use this in which case you'd want ab.append(name[i]) or you can use string concatenation like ab += " " + name[i] or using str.concat
1 last note of interest, you may have noticed your code as-is really likes to return and say that there's 1 item. This is because the above issues always (if the program doesn't break) leaves ab == '' and ''.split(' ') => [''] and thus len(ab.split(" ")) => 1
1 tip that I think would help in code comprehension is that the name variable here is not a single name string like it implies. It's actually a list[str]. I'd probably denote the variables something more like names_str: str vs names: list[str] or raw_names vs names. Then just use something like for name in names: and not worry about indexes. You can also use name.endswith('a') instead of name[-1] == 'a' for better readability.
Eventually you can combine these into a list comprehension for maximal succinctness -> len([name for name in names if name.endswith('a') or name.endswith('b')]).
words = ["ab", "bab", "pa", "pap"]
result = 0
for word in words:
if word[-1] in "ab":
result += 1
print(result)
As a list comprehension:
words = ["word1a", "word2b", "word3", "word4", "word5a"] # ['word1a', 'word2b', 'word5a']
filtered_words = [word for word in words if word[-1] in "ab"]
filtered_words = [word for word in words if word.endswith(("a", "b"))] # better, if you have multiple endings you want to search for with different lengths
len(filtered_words) # 3
name[i-1] is the previous name in the list, not the last character of the current name in the loop.
There's no need to append the matching names to a string. If you just need the count of matches, increment a counter variable.
You need to put a and b in quotes to make them strings, not variables.
names = input("Enter list of names: ")
name = names.split(" ")
matches = 0
print("Number of words:", len(name))
for cur_name in name:
if cur_name.endswith('a') or cur_name.endswith('b'):
matches += 1
print("Number of words that end with a or b: ", matches)
Use the endswith string method to detect if the last letter is "a" or "b"
names = ["bob","boba","larry","curly","moe"]
count = 0
for name in names:
if name.endswith("a") or name.endswith("b"):
count += 1
print(f"{count=}") # count=2
I want to filter a given sentence and extract all the string which are surrounded by single quotation marks and return a list.
For example, sample input:
"Welcome to 'Jungle', is a song by American rock band 'Guns N Roses' released in 1987."
Output:
['Jungle', 'Guns N Roses']
Explanation:
String - "Jungle" is surrounded by single quotation marks, so we need to pick this. Similarly - Guns N Roses. So the output is having 2 strings in its list. Another sample input:
"How are (you, doing today)"
Output:
[]
Explanation:
We do not have anything between single quotations so this returns empty list.
I tried using split function to split by single quotation, but realised that is not the right approach. Can you please help me how to do this in python?
Using Regex --> re.findall.
Ex:
import re
s = "Welcome to 'Jungle', is a song by American rock band 'Guns N Roses' released in 1987."
print(re.findall(r"'(.*?)'", s))
Output:
['Jungle', 'Guns N Roses']
You can try this way as well. This is the simplest programming way without using any library. You can give it a try:
full_string = input("Enter String: ")
quoted_strings = []
start = 0
quoted_string = ""
for letter in full_string:
if letter == "'" and start == 0:
start = 1
elif letter == "'" and start == 1:
quoted_strings.append(quoted_string)
quoted_string = ""
start = 0
elif start == 1:
quoted_string += letter
else:
pass
print("Entered Full String: " + full_string)
print("Quoted Strings: ", quoted_strings)
Although an answer is accepted just did for fun. Happy Coding !😊
IMHO, best approach when using regex is to avoid being "greedy".
import re
a = "'Jungle', is a song by American rock band 'Guns N Roses'"]
re.findall(r"'(.+?)'", a)
This will look for a word surrounded by quotations. e.g. it will skip empty quotations.
If you'd like to include empty quotations, use * instead of +.
We're using '?' to make the search less greedy.
so i have to create a code in which it reads every third letter and it creates a space in between each letter, my code creates the spaces but it also has a space after the last letter, this is my code:
msg = input("Message? ")
length = len(msg)
for i in range (0, length, 3):
x = msg[i]
print(x, end=" ")
My output was:
Message?
I enter:
cxohawalkldflghemwnsegfaeap
I get back
c h a l l e n g e
when the output isn't meant to have the last " " after the e.
I have read by adding print(" ".join(x)) should give me the output i need but when i put it in it just gives me a error. Please and Thank you
In Python, strings are one kind of data structures called sequences. Sequences support slicing, which is a simple and fancy way of doing things like "from nth", "to nth" and "every nth". The syntax is sequence[from_index:to_index:stride]. One does not even a for loop for doing that.ago
We can get every 3th character easily by omitting from_index and to_index, and have stride of 3:
>>> msg = input("Message? ")
cxohawalkldflghemwnsegfaeap
>>> every_3th = msg[::3]
>>> every_3th
'challenge'
Now, we just need to insert spaces after each letter. separator.join(iterable) will join elements from iterable together in order with the given separator in between. A string is an iterable, whose elements are the individiual characters.
Thus we can do:
>>> answer = ' '.join(every_3th)
>>> answer
'c h a l l e n g e'
For the final code we can omit intermediate variables and have still a quite readable two-liner:
>>> msg = input('Message? ')
>>> print(' '.join(msg[::3]))
Try
>>> print " ".join([msg[i] for i in range(0, len(msg), 3)])
'c h a l l e n g e'
How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word, the word will be printed with all the undiscovered letters as "-".
I am not asking for a way to make my idea/code of the whole project better, just a way to, as i said, print that one specific character of the string.
print(yourstring[characterposition])
Example
print("foobar"[3])
prints the letter b
EDIT:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(str(c) + " " + mystring[c]);
Outputs:
2 l
3 l
9 l
And more along the lines of hangman:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(mystring[c], end="")
elif mystring[c] == " ":
print(" ", end="")
else:
print("-", end="")
produces
--ll- ---l-
all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e.
text="hello"
print(text[0])
print(text[2])
print(text[1])
returns:
h
l
e
Well if you know the character you want to search you can use this approach.
i = character looking for
input1 = string
if i in input1:
print(i)
you can change the print statement according to your logic.
name = "premier league"
for x in name:
print(x)
Result shown below:-
To print specific characters of the given string. For example to print 'l' from the given string
name = "premier league"
for x in name:
if x == "l":
print("element found: "+x)
I'm trying to make a program using python for class that works like this:
'Enter a word: " (EG Stack)
Then it outputs
S
St
Sta
Stac
Stack
I believe that it would use a looping function, but I'm completely stuck!
You can use slicing to achieve your output. Each iteration of the for loop increments an index variable (i below), and this is used to display ever increasing slices from the string.
>>> word = 'Stack'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
St
Sta
Stac
Stack
>>> word='Slicing'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
Sl
Sli
Slic
Slici
Slicin
Slicing
You can read about slicing in the Python tutorial.
msg = raw_input("Enter a word: ") #raw_input will convert the input into a string
#otherwise it would crash without quotation marks
word = "" #Initialize a variable
for letter in msg: #Cycle through each letter
word += letter #Adds that letter to your string
print(word) #Prints out the current letters
http://pastebin.com/CDzNfdbJ
Got it, I don't really understand it, but it works.