This question already has answers here:
Python Regex to find a string in double quotes within a string
(6 answers)
Closed 6 years ago.
I'm trying to write a function where the input has a keyword that occurs multiple times in a string and will print the stuff that has double quotation marks between them after the keyword. Essentially...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
If its possible to have the outputs as its own line that would be better.
Here's what I have so far:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
Please don't suggest import. I do not know how to do that nor know what it is, I am a beginner.
Let's take some sample input:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
I believe that one " was missing from the sample input, so I added it.
As I understand it, you want to get the strings in double-quotes that follow the word keyword. If that is the case, then:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
How it works
Let's look at the first piece:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
By splitting Input on keyword, we get, in this case, three strings. The second string to the last are all strings that follow the word keyword. To get those strings without the first string, we use subscripting:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
Now, our next task is to get the part of these strings that is in double-quotes. To do that, we split each of these strings on ". The second string, the one numbered 1, will be the string in double quotes. As a simpler example, let's take these strings:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
Next, we put these two steps together:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
We now have the strings that we want. The last step is to print them out nicely, one per line:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
Limitation: this approach assumes that keyword never appears inside the double-quoted strings.
Related
This question already has answers here:
How do I remove a substring from the end of a string?
(23 answers)
Closed 2 years ago.
I am kind of noob in python and struck in middle of code. I want to trim my string.
For example- my string is "bangalore store 1321" and i want to trim it to "banglore"
Looks like you want to keep the first word (which is not "trimming" though). So you do two things
break the string into a list of words (where "word" is something separated by spaces)
take the first element of that list
words = mystring.split(' ')
result = words[0]
For a slicing answer:
def sub_string(str, start,end):
return str[start:end]
You can also use split, by definition, this splits by spaces, if any other delimiter needed, you can identity it inside the split arguments split(',')
def split_string(str):
return str.split()
This function will return an array of strings. Choose whichever you want from this array
str="bangalore store 1321"
print(str.split(' ')[0])
Output
bangalore
You can use str's partition method to avoid creating a list like str.split
>>> first_word, _, _ = s.partition(' ') # _ is a convention for a throwaway variable
>>> print(first_word)
bangalore
str.partition takes one argument - the separator - and returns the parts of the string before and after the first occurrence of the separator.
I have a question that ask the user to input a string THE and split it as three different string, output like this T,H,E I tried but output same with input.
def func():
str1=input("Enter String : ")
','.split(str1)
print(str1)
func()
Output
THE
And second question is that ask the user to enter a string T H E S T R I N G and the output should THE STRING when one space occurs remove it and if more then one then replace it whit single space.
Here is my code.
def func2():
str2=input("Enter String :")
for i in str2:
if(i.isspace==True):
del(i)
else:
str2=str2+i
print(str2)
func2()
output is.
T H E S T R I N GTHESTRING
I have no idea how to correct it.
You cannot store the value after splitting and not printing it.
Just change ','.split(str1) with str1 =str1.split(',') and print str1.
Read the documentation for the split method: it doesn't apply to your first problem at all. Instead, the solution is much simpler: take the individual characters and join them with commas:
char_list = list(str1)
str2 = ','.join(char_list)
... and print or return str3. Yes, this can be shortened; I'm teaching you the individual steps.
As the posting guidelines tell you, each question must have a separate posting. I'll leave the other answer for your other posting.
There's a distinction between in-place and standard operators. In-place functions actually change in the input, while standard operators give a result as output, and that output then has to be assigned or passed to something else for it to be used. (Also, you don't have the syntax correct; it should be 'str1.split(',')) The split operator is a standard operator; 'str1.split(',') doesn't affect the value of str1, but instead creates a new result. Since you're not doing anything with that result, it gets thrown away. You could do split_string ='str1.split(',') and then print(new_string) or just print('str1.split(',').
Also, the problem statements "split it as three different string" and "output like this T,H,E" are contradictory. If you want a list of three strings, that would be ['T','H','E']. Saying you want an output of T,H,E makes it sound like you want a single string with commas between the letters.
This question already has answers here:
How to strip all whitespace from string
(14 answers)
Closed 4 years ago.
Basically, I'm trying to do a code in Python where a user inputs a sentence. However, I need my code to remove ALL whitespaces (e.g. tabs, space, index, etc.) and print it out.
This is what I have so far:
def output_without_whitespace(text):
newText = text.split("")
print('String with no whitespaces: '.join(newText))
I'm clear that I'm doing a lot wrong here and I'm missing plenty, but, I haven't been able to thoroughly go over splitting and joining strings yet, so it'd be great if someone explained it to me.
This is the whole code that I have so far:
text = input(str('Enter a sentence: '))
print(f'You entered: {text}')
def get_num_of_characters(text):
result = 0
for char in text:
result += 1
return result
print('Number of characters: ', get_num_of_characters(text))
def output_without_whitespace(text):
newtext = "".join(text.split())
print(f'String without whitespaces: {newtext}')
I FIGURED OUT MY PROBLEM!
I realize that in this line of code.
print(f'String without whitespaces: {newtext}')
It's supposed to be.
print('String without whitespaces: ', output_without_whitespace(text))
I realize that my problem as to why the sentence without whitespaces was not printing back out to me was, because I was not calling out my function!
You have the right idea, but here's how to implement it with split and join:
def output_without_whitespace(text):
return ''.join(text.split())
so that:
output_without_whitespace(' this\t is a\n test..\n ')
would return:
thisisatest..
A trivial solution is to just use split and rejoin (similar to what you are doing):
def output_without_whitespace(text):
return ''.join(text.split())
First we split the initial string to a list of words, then we join them all together.
So to think about it a bit:
text.split()
will give us a list of words (split by any whitespace). So for example:
'hello world'.split() -> ['hello', 'world']
And finally
''.join(<result of text.split()>)
joins all of the words in the given list to a single string. So:
''.join(['hello', 'world']) -> 'helloworld'
See Remove all whitespace in a string in Python for more ways to do it.
Get input, split, join
s = ''.join((input('Enter string: ').split()))
Enter string: vash the stampede
vashthestampede
There are a few different ways to do this, but this seems the most obvious one to me. It is simple and efficient.
>>> with_spaces = ' The quick brown fox '
>>> list_no_spaces = with_spaces.split()
>>> ''.join(list_no_spaces)
'Thequickbrownfox'
.split() with no parameter splits a string into a list wherever there's one or more white space characters, leaving out the white space...more details here.
''.join(list_no_spaces) joins elements of the list into a string with nothing betwen the elements, which is what you want here: 'Thequickbrownfox'.
If you had used ','.join(list_no_spaces) you'd get 'The,quick,brown,fox'.
Experienced Python programmers tend to use regular expressions sparingly. Often it's better to use tools like .split() and .join() to do the work, and keep regular expressions for where there is no alternative.
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 3 years ago.
I would like to know how can I get from a string and using reg expressions all values until the comma starting from the end. See below example, I would like to get the value "CA 0.810" into a variable:
prue ="VA=-0.850,0.800;CA=-0.863,0.800;SP=-0.860,0.810;MO=-0.860,0.810;SUN=MO -0.850,CA 0.810"
So far, I have the below code:
test = re.findall('([0-9]+)$',prue)
print test
However, I only get below output:
['810']
Could you please advise how can I get "CA 0.810" into the test variable?
You can do this using the split method. From the docs, it will:
Return a list of the words in the string, using sep as the delimiter string.
So if you can take your string:
prue = "VA=-0.850,0.800;CA=-0.863,0.800;SP=-0.860,0.810;MO=-0.860,0.810;SUN=MO -0.850,CA 0.810"
you can do :
prue.split(",")
which will return a list of the strings split by the commas:
['VA=-0.850', '0.800;CA=-0.863', '0.800;SP=-0.860', '0.810;MO=-0.860', '0.810;SUN=MO -0.850', 'CA 0.810']
So if you just want the last item ('CA 0.8101') into a variable named test, you can just take the last element from the list by indexing with -1:
test = prue.split(",")[-1]
test is now: 'CA 0.810'
Hope this helps!
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 9 years ago.
I am trying to write a parser which takes expressions as a input from file.
expressions can be A=B=10 or B=(C-A)-4 etc.
What i have tried so far is . I am reading a file IP.txt
import re
opert = '+-/*()_='
fileName = "input.txt"
f = open(fileName,'r')
variableDict = {}
lines = f.readlines()
for i in lines:
for x in re.finditer(r'[A-Z_]\w*', i):
print x.group() # prints list containing all the alphabets.
for z in re.finditer(r'[0-9]\d*', i):
print z.group() # prints list containing all the numbers.
for c in i:
if c in opert:
print c # prints all the operators.
# '_' has special meaning. '_' can only be used before numbers only like _1 or _12 etc
#And i have parsed this also using
print re.findall(r'[_][0-9]\d+',i) # prints the _digits combination.
Now the problem is i have struck at how should i proceed with expression evaluation.
First some rule which i must mention about above inputs are.
No line should be greater then 50 characters.
Left most operator will always be '=' assignment operator.
'=' always Preceded by variables[A-Z],operators are {'+','-','/','*','_'}, digits {0-9}.
How should i first extract the first variable then push it into python list then '=' operator,then either '(','A-Z' push it into stack and so on
Could someone help me with this problem. I am overwhelmed with problem..
If any one is not able to understand the description please goto this link
So, you asked about the stack problem, which of course you need for evaluation. I would do something like this:
import re #1
stack = [] #2 FIX: NOT NECESSARY (since fourth line returns a list anyway)
inputstr = "A=B=C+26-(23*_2 )-D" #3
stack = re.findall(r'(?:[A-Z])|(?:[0-9]+)|(?:[/*+_=\(\)-])', inputstr) #4
while len(stack): #5
print stack.pop() #6
First three lines are some init stuff only. After that, I would make a stack with regex in the fourth line. (?:[A-Z]) matches variable, (?:[0-9]+) matches number (which may have more than one digit) and (?:[/*+_=\(\)-]) matches all the operators. Braces are escaped, and - is on the end, so you don't have to escape it.
Fifth and sixth line prints the stack.
I used (?: ...) because I don't want to match either group. Hard to explain - just try to run it without ?: and you will see the effect.