re.findall working in console but not in script? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm probably missing something very basic here, but here goes:
I'm using Python 2.7 and regex to identify digits within a string.
In the console, I type in:
>>> newstr = 'NukeNews/File_132.txt'
>>> int(re.findall(r'\d+',newstr)[0])
132
Which is what I expect.
However, in the script I'm running, I have the strings stored in a dictionary, linedict. I'm running this script:
news_id=[]
for line in line_vec:
print linedict[line]
newstr= linedict[line]
id_int = re.findall('r\d+',newstr)
print id_int
news_id.append(id_int)
It's a long list, but the output looks like:
NukeNews/File_132.txt
[]
So - the correct string is registered, but it's not matching on anything.
I was calling the first item in the list earlier (to match the console input of int(re.findall(r'\d+',newstr)[0]), but the script is telling me that the regex didn't find any instances of the digits in the string. I would expect this to return:
NukeNews/File_132.txt
['132']
Any idea why it's not working as expected? When I try running re.match(r'/d+',newstr) I also get an empty group (following the groups example on https://docs.python.org/2/library/re.html).
Edit: As pointed out, this is a case of not being careful with 'r' and r'*'. I'm just going to leave this up in case anyone else googling "why does my regex work in console but not in script" forgets to check this typo, like I did.

You've got your r inside the quotes so instead of getting a "raw string" you're getting a string with an 'r' in it ...
id_int = re.findall('r\d+',newstr)
# ^
# should be:
id_int = re.findall(r'\d+',newstr)
your "console" version also only takes the first of the found matches compared to your "script" version which appends the entire list.

Related

Reverse a string with users input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I decided to take on some programming projects and decided to follow this guide:
https://www.dreamincode.net/forums/topic/78802-martyr2s-mega-project-ideas-list/
I started with the first project, which is to reverse a string, pretty simple stuff as you can find out how to do that in the documentation. IE.
txt = "Hello World"[::-1]
print(txt)
dlroW olleH
s = "health" [::-1]
print(s)
htlaeh
And So on... There's two questions really. In this guide i'm not to sure if they just wanted you to reverse the string. It seems like they want Input? For the user to Enter the String.
In this case i thought it might be something like this:
string = Input("Enter a string")
print(s [::-1])
How ever this did not work, Not to sure how to implement this in Python 3.8.2. Could someone let me know and how they did it that would be great.
Thank you.
Your code has a space between s and the indices you want. You also have two variable names, s and string. Choose one. Finally, Input must be lowercase. Change it to this:
string = input("Enter a string")
print(string[::-1])
Your print statement needs some modifications.
Here it goes-
print(string[: :-1])

Issue with join() function? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm attempting to bulk-download some csv files from a website. I've included a generic form of the first few lines of code I'm using below.
import urllib3
import os.path
def downLoadToDir(save_path,foo):
http = urllib3.PoolManager()
os.makedirs("".join(save_path, foo)
# Set up url and path for download
VarUrl = "".join("http://url.com/ajax/exportKR2CSV.html?t=", foo)
VarPath = "".join(save_path, foo, '/',foo, '.csv')
Ideally this should set up a folder under the specified filepath, and set up two variables I use later. However, I keep getting this error:
File "url_download.py", line 10
VarUrl = "".join("url.com/ajax/exportKR2CSV.html?t=", foo)
^
SyntaxError: invalid syntax
Based off of other examples I've seen online, this seems correct to me. Nothing seems to make it happy. Where am I going wrong? Thanks
You're missing a right parenthesis at line:
os.makedirs("".join(save_path, foo)
Also, the join method takes only one list argument, and you are passing two arguments here. You should make the two strings a list before passing to join as one argument:
os.makedirs("".join([save_path, foo]))
The same issue goes for the following lines that also use join.
You are not closing the bracket on line 7. Python is still looking for the close bracket and the "" is not what the compiler expects to see.
use os.makedirs("".join(save_path, foo))

Using regex to get numbers from a string using Python, incorrectly prints full string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Objective
I'm looking to use the regular expression \d+ to extract just the digits from the string, answer_40194.
Problem
I'm targeting a form element with Selenium and I'm printing the formID to the Terminal, but after the line re.findall('\d+', formID) I expect formID to be just the numbers 40194, but instead I'm getting the entire string answer_40194.
script.py
import selenium
import re
form = browser.find_element_by_tag_name('form')
formID = form.get_attribute('id')
re.findall('\d+', formID)
print formIDNumber
You need to assign the result to a variable, e.g.
var1 = re.findall('\d+', formID)
print(var1)
This will generate a list, if you only want one result, use
var1 = re.search('\d+', formID)
print(var1.group(0))
The latter is called a regular expression object, hence the .group(0), see the documentation on python.org for more information.

Python2: TypeError while checking dictionary value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I have the following Python code to iterate over a nested dictionary and grab a value from the second child:
ret = some_dict
for item, val in ret.items():
for item2, val2 in val.items():
print val2['result']
When I test this in IPython or the interactive Python interpreter, the code works fine, and prints the value of val2['result'] for each item in the dictionary. However, when I use this block of code in a Python program I get the following error when trying to print val2['result']:
TypeError: string indices must be integers, not str
If I print json.dumps(val2, indent=2), I can see that the dictionary is formed correctly. Attempting to use dict() to cast val2 to a dictionary in the script also fails with the following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I'm not entirely sure what I'm doing wrong at this point, since the code works in the interactive interpreter. I am using Python 2.7.6, and the use case is iterating over a dictionary returned by the Saltstack Python client.
Believe the message: it is telling you that val2 is a string when you think it is a dict. This is almost certainly due to your JSON data not being structured as you think it is.

for loop find in list with if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have the following question:
considering the given list :
list = ['12','8','3']
why does print('8' in list) returns True
whereas
for i in range(5):
if '8' in list == True:
(code)
doesn't execute my code inside the if loop ?
Could someone explain me why, and how could I make this work ?
Maybe this question has already been asked but I don't see with which keywords I should search for it.
Thanks for the help :-)
You seem to have some logical errors in your code, so I'll try to outline what you should be doing.
You shouldn't name variables str or list or int because they might conflict with Python's built in keywords.
Your check did if '8' in list, but that will test if the string 8 is in the list, not the number. Drop the apostrophes.
You don't have to put if 8 in list in a loop, it'll do the looping and testing for you.
Solution
To check if a number is in a list, you can use python's built in in keyword, your write your own code to do the checking.
Remember not to use keywords like list, so I've changed the name to myList in these examples.
Using in
if 8 in myList: # Note that you don't have to say == True
print('8 is in the list!')
Or using for i in myList)
for i in myList:
if i == 8:
print('8 is in the list!')**
Or using for i in range(len(myList))
for i in range(len(myList)):
if myList[i] == 8:
print('8 is in the list!')

Categories

Resources