Error in using slice assignment in strings - python

website = 'http://www.python.org'
website[18:] = 'com'
The error says:
'str' object does not support item assignment.
Why is this code snippet not legal?

Because strings are immutable. Do it like this:
>>> website = 'http://www.python.org'
>>> website = website[:18] + 'com' # build a new string, reassign variable website
>>> website
'http://www.python.com'

If you prefer not to count how many characters to stop before you reach .org
you can use
website=website[:len(website)-4]+".com"

Related

Splitting website url to keywords, multible splits

I am currently creating a tool which scans the URL of a website and returns the keywords as a list. For example google.com/images then the tool should give out:
{"google", "images"}
I knew how to filter the .com part out, but I have the problem that I can't split the split parts again. So I end up with the results of the first split. How do I split these parts again?
First run split(".") -> {"google", "com/images"}
Second run split("/") -> {"google", "com", "images"}
because then I can filter things like the .com part out. I'm writing this in Python and this is my code atm.
First the error:
" AttributeError: 'list' object has no attribute 'split' "
so the problem is that this is an list object and I can't split this again.
Now the code
url_content = input('Enter url: ')
url_split1 = url_content.split('.')
url_split2 = url_split1.split('/')
url_split3 = url_split2.split('-')
url_split4 = url_split3.split('&')
filtered = {'com', 'net'}
print(url_split4)
for key in url_split4:
if key not in filtered:
print(key)
You can use replace:
url_content = input('Enter url: ').replace('/','.').replace('-','.').replace('&','.')
and then split it once:
url_split1 = url_content.split('.')
You can use either use python's builtin regular expressions library as follows.
import re
re.split('\.|\&|\-|/', url_content)
or you may use the string replace method.
url_content.replace(".", "/").replace("&", "/").replace("-", "/").split("/")

Python Selenium: Alternative to string formatting for lists?

I am trying to take the value from the input and put it into the browser.find_elements_by_xpath("//div[#class='v1Nh3 kIKUG _bz0w']") function. However, the string formatting surely doesn't work, since it's the list, hence it throws the AttributeError.
Does anyone know any alternatives to use with lists (possibly without iterating over each file)?
xpath_to_links = input('Enter the xpath to links: ')
posts = browser.find_elements_by_xpath("//div[#class='{}']").format(devops)
AttributeError: 'list' object has no attribute 'format'
Looks like the reason of error is that you are placing the format function in the wrong place, so instead of operating on string "//div[#class='{}']" you call it for the list returned by find_elements_by_xpath. Could you please try to replace your code with one of the following lines ?
posts = browser.find_elements_by_xpath("//div[#class='{}']".format(devops))
posts = browser.find_elements_by_xpath(f"//div[#class='{devops}']")

Selenium - How to add integer variable in xpath using python

Im new with selenium/python and that my problem:
I have a simple site with a couple of news.
I try to write script that iterates over all news, open each one, do something and goes back to all other news
All news have same xpath, difference only with last symbol - i try to put this symbol as variable and loop over all news, with increment my variable after every visited news:
x = len(driver.find_elements_by_class_name('cards-news-event'))
print (x)
for i in range(x):
driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a["'+i+'"]**').click()
do something
i = i+1
Python return error: "Except type "str", got "int" instead. Google it couple of hours but really can't deal with it
Very appreciate for any help
You are trying to add a string and a int which is is why the exception. Use str(i) instead of i
xpath_string = '/html/body/div[1]/div[1]/div/div/div/div[2]/div/div[3]/div/div[1]/div/**a[{0}]**'.format(str(i))
driver.find_element_by_xpath(xpath_string).click()
In the above the {0} is replaced with str(i). You can use .format to substitute multiple variables in a string by providing them as positional values, it is more elegant and easy to use that using + to concatenate strings.
refer: http://thepythonguru.com/python-string-formatting/

AttributeError: 'dict_values' object has no attribute 'rsplit'

I am trying to a reverse split of a URL generated from a text file and am getting the above error when printing that split value. I have tried making a string from the URL and splitting that, but this causes the GUI to freeze completely and not even produce an error message. My code is here:
a = URLS.rsplit('=', 1)
The code I used when attempting to resolve a string from the URL then split that is here:
urlstr = str(URLS)
a = urlstr.rsplit('=', 1)
print(a)
Can anyone tell me why I cant split the URL using the split method (the URLS were defined in a dictionary) and/or why creating a string and then splitting that is not working?
Thanks
The error suggests that URLS is not a string, but rather a dict_values object. I think that's what you get when you call the values method of a dictionary (in Python 3). A values view is an iterable object, so you probably want to loop over it, with something like:
for url in URLS:
a = url.rsplit("=", 1)
# do stuff with a here
Or if you want a list of the various a values, you could use a list comprehension:
a_lst = [url.rsplit("=", 1) for url in URLS]
A dict_values object is a sequence. It does not have an rsplit method, though str objects do.
Really though, instead of using rsplit, you probably should be using urllib.parse to extract information from your URLs.
For example,
>>> import urllib.parse as parse
>>> url = 'http://stackoverflow.com/questions?x=foo&y=bar'
>>> parse.urlsplit(url)
SplitResult(scheme='http', netloc='stackoverflow.com', path='/questions', query='x=foo&y=bar', fragment='')
>>> parse.urlsplit(url).query
'x=foo&y=bar'
>>> parse.parse_qs(parse.urlsplit(url).query)
{'x': ['foo'], 'y': ['bar']}
So, if URLS is a dict, then you can loop through the values and extract the parameter values using
>>> URLS = {'a': 'http://stackoverflow.com/questions?x=foo&y=bar'}
>>> for url in URLS.values():
... print(parse.parse_qs(parse.urlsplit(url).query))
...
{'x': ['foo'], 'y': ['bar']}
Unlike rsplit, parse_qs will allow you to properly unquote percent-encoded query strings, and control the parsing of blank values.

Python Query ( string)

I am working with python plugins.I have my field variable = "t_0"."survey" I wanted to store only survey into another variable.Which function to use to get survey from "t_0"."survey"?
I tried a=field.split(".") when i try to print a ,it gives
<PyQt4.QtCore.QStringList object at 0x01247228>
Is there any delete function or to find position of "." from the string..?
If i try lstrip() or ljust() ,it gives error saying
AttributeError: 'QString' object has no attribute 'lstrip'..
If a is a QString, then calling a.split produces a QStringList, just as calling split on a Python str produces a list:
>>> qstr = QString("t_0.survey")
>>> slist = qstr.split(".")
>>> slist
<PyQt4.QtCore.QStringList object at 0x00BBCD88>
You can either cast QStringList to a Python list:
>>> list(slist)
[PyQt4.QtCore.QString(u't_0'), PyQt4.QtCore.QString(u'survey')]
or just extract the second element:
>>> slist[1]
PyQt4.QtCore.QString(u'survey')
And perhaps get rid of the QString wrapping:
>>> unicode(slist[1])
u'survey'
If your field variable is of type QString the below code works fine for me.
QString str = "a,b,c";
QStringList list1 = str.split(",");
Output = [ "a","b", "c" ]
Try doing type(field) in your python interpreter and show us the output.
OR type cast your variable to str like this a=str(field).split(".")
It seems like 'a' is not really a String, but some other object generated by the PyQt library (maybe an input field ?). If you can find a way to get a real String out of this field (a.value(), a.text(), or something like that), you should be able to use split.

Categories