Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to implement a function extract_words() that takes in a string of text as its single parameter and returns a list of the words in that string, like this:
input: "There're six words in this string."
output: ["There're", 'six', 'words', 'in', 'this', 'string']
But when I write it like the following and run it in Jupyter Notebook, it shows like this:
I learned how to write this function by the following, so I tried this in Jupyter, and it shows correct:
So may I ask what's wrong with my code, and how to fix it?
The problem is the cast to str inside your function. Just do return inputStr.split() and should works.
def __extract_words__(inputStr):
return inputStr.split()
inputStr = "There're six words in this string."
__extract_words__(inputStr)
There is nothing to replace. Those are escape characters because you returned a string
You want to return the split list as an actual list, not a str() - return inputStr.split()
Look at the docs for the typing module so the type checker would have shown you the issue more clearly. I.e. your function was actually returning a string.
I think what is confusing you is that you needed to use str() when you print the result, but that could be fixed like this
print(f'The list of words is {res}')
That being said, you don't really need your own function if the goal is to only print
test_string = input('text> ')
print(f'The list of words is {test_string.split()}')
Also, the __function_name__ syntax (surrounding underscores) should be reserved for "magic functions" rather than user functions
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to split a string without breaking any words in the string. After reading in a text file called "output.txt.", when I use the splitlines() function as below, it breaks the words at the line boundaries (for example, it breaks the word "from" and keeps "fr" on a first line, moving "om" to the next line.
with open('output.txt', 'r') as file:
temp = file.read()
x = ' '.join(temp.splitlines())
I am new to Python; using Python 3.6.8. Is there a way to modify the splitlines() such that it breaks the string at line boundaries and returns a list of splitted strings, but it does not break words in the original string? Thanks.
I don't know if this is the awnser you're looking for, but you can use the .split() function on a string and give a parameter to split on. So if you have:
"Hello this is a string"
and you call .split(" ") on it, it returns:
["Hello", "this", "is", "a", "string"]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How do I search and replace using built-in Python methods?
For instance, with a string of appleorangegrapes (yes all of them joined),
Replace "apple" with "mango".
The .replace method only works if the words are evenly spaced out but not if they are combined as one. Is there a way around this?
I searched the web but again the .replace method only gives me an example if they are spaced out.
Thank you for looking at the problem!
This works exactly as expected and advertised. Have a look:
s = 'appleorangegrapes'
print(s) # -> appleorangegrapes
s = s.replace('apple', 'mango')
print(s) # -> mangoorangegrapes
The only thing that you have to be careful of is that replace is not an in-place operator and as such it does not update s automatically; it only creates a new string that you have to assign to something.
s = 'appleorangegrapes'
s.replace('apple', 'mango') # the change is made but not saved
print(s) # -> appleorangegrapes
replace can work for any string, why you think that it doesn't, here is the test:
>>> s='appleorangegrapes'
>>> s.replace('apple','mango')
'mangoorangegrapes'
>>>
Don't you see that you received your expected result?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am very new to python, and want to make a program that swaps the lower and upper case.
That is no problem, but I am having trouble with shuffling the words.
This is my code:
def swap_lower_upper(zin):
print(zin.swapcase())
def shuffle(zin):
import random
lijst = list(zin)
random.shuffle(lijst)
print (lijst)
swap_lower_upper('Dit IS een test')
shuffle('Dit IS een test')
I've tried many things but I can't seem to let the shuffle work.
I would greatly appreciate your help!
Thanks in advance.
I'm assuming the issue is that this is sorting letters overall rather than simply sorting the words. Rather than converting the string zin to a list by using the built-in list function, what you could do instead would be to split the string by spaces, using the .split() function of the string type. Then, after shuffling, for printing neatly, you could rejoin these words into a single string using the .join() function of the string type.
So something like this:
def swap_lower_upper(zin):
print(zin.swapcase())
def shuffle(zin):
import random
lijst = zin.split(" ")
random.shuffle(lijst)
print (" ".join(lijst))
swap_lower_upper('Dit IS een test')
shuffle('Dit IS een test')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having issues extracting numbers from a string to create a new field using field calculator in ArcGIS. The values being extracted have to remain as a string. The issue that I am having is that there is no consistency in the number of characters leading up to and following the numbers I wish to extract. The only consistency there is within the string is a comma that follows the desired number.
So far my code is as follows:
def get_num_from_string(string):
num = ''
for i in string:
if i in '1234567890':
num+=i
return num
This code is unsuccessful in accomplishing my goal I need the code to step through each character in the string and return only numbers until the comma is reached. For example if the original string is "River Lot 489, 11756 MB CODE" I want my output string to read "489".
suppose you have the String
>>> test = "12hel34l0"
To get all the digits in the String, simply do
>>> print([d for d in test if d.isdigit()])
['1', '2', '3', '4', '0']
If you want it to be a String again instead of a list, use join
>>> print(''.join([d for d in test if d.isdigit()]))
12340
Edit:
"River Lot 489, 127756 MB CODE" I want my output to simply be "489"
To match this, I simply change the following method to test.split(",")[0]. You have to provide more information how your data looks like and if you want to get the digits before the first comma every time.
Implemented in your method.
def get_num_from_string(string):
return ''.join([d for d in test.split(",")[0] if d.isdigit()])
Testing your provided example
>>> test = "River Lot 489, 127756 MB CODE"
>>> print(get_num_from_string(test))
489
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The following is my code:
string1 = (input("What is your name?")) #creates a string, stores the name in it
first1 = string1[:1]
string2 = (input("What is your last name?"))
first3 = string2[:3]
from random import randint
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
print (sentence)
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
print (sentence)
It works, but I am having some trouble. I need to loop this 5 times - but it doesn't work for some reason!
P.S. Python 3!
You are creating a tuple called sentence, rather than a string
If you change that line to this:
sentence = "".join((str(randint(0,9)), first1.lower(), first3.upper()))
It will create a string that has no gaps, like so when printed:
What is your name?First
What is your last name?Last
5fLAS
You are creating a list, not a string so it seems logical that you get issues when trying to print it...
To append to a string you can do that :
sentence = str(randint(0,9))+(first1.lower())+(first3.upper())
In Python, you don't give a type to your variables, it depends of what you put INTO them.
In Python, elements between parenthesis "()" are considered as TUPLE (a type similar to a list, but that cant be modified), "[]" stands for a list, "{}" stands for a dictionnary. So you must NOT put parts of a string between parenthesis and separated with commas or you will turn them into a list of words. Instead you can use "+" that means to Python that you are making a string concatenation. Also note that i casted your random number into string. If you give 3 strings separated by "+" Python will automatically detect sentence as a String. Wp you've created a string !
If you have a list and want to get rid of the spaces you can also use :
"".join(yourlist)
However i don't recommend it here, you would be creating a list and using a join for nothing since you can create a string from the begining.
Edit: As for the loop, we can't answer if you don't copy paste the code of the loop and the error, it could be a million things.