Tagged Questions
-1
votes
1answer
28 views
Python def litCritic [on hold]
for this problem I have to define a function that returns the frequency of a specific word from the body of a text. Frequency being the number of times a word appears regardless of it being upper or ...
3
votes
2answers
24 views
pandas: extract or split char from number string
I have a dataframe selected from a sql table that looks like this
id shares_float
0 1 621.76M
1 2 329.51M
in other word,
[(1, '621.76M'), (2, '329.51M')]
I want to split the ...
0
votes
1answer
19 views
How to use string formatting to dynamically assign variables
In Python, I am populating an object to model the configuration, environment and other aspects related to rsyslog on the local machine (RHEL 6.4 Python 2.6.4) I loop through many instances of the ...
-1
votes
1answer
27 views
How to copy what Python last printed and put it to a string
The reason for this is for a string that prints something different than what it actually is, which I have strangely encountered. So what I want is something that gives an output like:
>>>x ...
0
votes
1answer
20 views
How can I convert a list of hexadecimal strings to a single string with escape characters?
I have a list:
list = ['0x01','0x02','0x03']
But I need to convert it to a string with form:
string = "\x01\x02\x03"
If someone could help me please, I'm really stuck.
Thanks.
0
votes
1answer
24 views
Delete strings from a list who do not contain certain words?
For example something like this (although it doesn't work):
list1 = ['hello, how are you?', 'well, who are you', 'what do you want']
desiredwords = ['hello', 'well']
list2 = [x for x in list1 if ...
0
votes
3answers
42 views
How to simultaneously loop over different lists?
I'm trying to loop over a list of strings:
someplace["Canada", "USA", "England"]
for charNum in range(len(lst)): #charNum the length of the characters
print(lst[charNum])
for country in ...
1
vote
1answer
25 views
How is this string being formatted in python
I am going through a tutorial for a python library. Found this example code :
>>> device = monitor.poll(timeout=3)
>>> if device:
... print('{0.action}: {0}'.format(device))
...
...
0
votes
2answers
39 views
Output matching keyword from a string in python
I have this basic program. It takes a list of keywords, looks for those keywords in a string and if it finds a keyword, it does something based on that match.
I always forget the needed steps to ...
0
votes
4answers
43 views
Check that a string starts with a drive letter in Python
I'm writing a script that will take a list of file paths as input. I want the script to make sure the strings in the input file are, or at least appear to be, valid full Windows paths, that include ...
1
vote
2answers
68 views
Python - Variable being printed over string
I am using python 2.7 and i have a problem that i haven't encountered before, when i print a certain string and then a variable on the same line the variable is printed over the string. e.g. the ...
6
votes
1answer
45 views
What is the best way to convert a printed list in Python back into an actual list
So given the a a textual representation of a list
['cellular organisms', 'Bacteria', 'Bacteroidetes/Chlorobi group', 'Bacteroidetes', 'Bacteroidia', 'Bacteroidales', 'Bacteroidaceae', ...
1
vote
1answer
35 views
Modifying a Regex Expression
i have several strings to match certain expressions where i want to match and extract 2 words after the prepositions along with the preps themselves.. And they do a good job too . But i need to modify ...
-2
votes
4answers
29 views
python list of lists of strings divide by 2 [on hold]
How do I divide number of list of lists of strings by 2?
For example:
[['the time has come', ' the walrus said to talk of many things', ' of shoes - and ships - and sealing wax', 'of cabbages', ' ...
0
votes
1answer
52 views
Generating a string with python using loops with logic conditions issues against join function alternative?
I coded a function in order to generate Lagrange interpolation expressions.
So I got:
def polinomioLagrange(Xs, Ys, t):
for k in range(len(Xs)):
if k >0:
expresion = ...
-5
votes
0answers
38 views
Checking for alphabetic characters in a string. Returns true for '!!!!!!!!' [on hold]
There are string methods that allow you to check whether there is at least one upper or lower/case character in the string. They work fine on strings like 'Hello' and 'hello', but if I enter a string ...
-2
votes
3answers
44 views
Python: Handling more than 2 parameters in reduce() [on hold]
I wish to write a solution to find the number (if exists) whose value is equal to sum of rest of consecutive values in the list. The solution desires the longest sequence.
For example, if list a is
...
2
votes
4answers
54 views
How do I return the earliest letter in the alphabet from a choice of letters?
I am doing an exercise the requires me to return the most frequent letter in a string of letters. In the event that there are two letters that appear with the same frequency, the 'tiebreaker' is ...
0
votes
2answers
62 views
Python: loop over a list of string and using split()
I'm trying to split the elements of a list:
text = ['James Fennimore Cooper\n', 'Peter, Paul, and Mary\n',
'James Gosling\n']
newlist = ['James', 'Fennimore', 'Cooper\n', 'Peter', 'Paul,', ...
0
votes
1answer
41 views
finding anagrams of a string in python
i wrote the code for anagrams but it is not giving the result for some test cases
import itertools
def find_all_anagrams(words, word):
if word is None:
return []
else:
...
1
vote
2answers
46 views
Creating new lines with full stops (period) in text files [on hold]
I have a sentence in a text file that I want to display in python, but I want to display it so after every full stop(period) a new line starts.
For example my paragraph is
"Dr. Harrison bought ...
2
votes
3answers
49 views
Better way to find common words in a tuple?
I completed an exercise in which I found and returned the common words between two strings in alphabetical order as a string, separated by commas. Though I was able to do it correctly, I am wondering ...
-1
votes
2answers
54 views
How Do I change a sum for string for it to work? [on hold]
import time
import random
def welcome():
ready="no"
while ready=="no":
print("Welcome To Encounter Simulator Inc. Where We Provide You with combat..")
print("Readying Start Up Sequence....")
...
1
vote
1answer
42 views
Performance of Pypy's islower(), isupper()
I have a program in which str.isupper() is called in a very tight loop, and takes around 25% of my running time.
It strikes me that isupper and islower are much slower than other isX methods, such as ...
3
votes
6answers
89 views
How to display a list vertically?
I have a list of letters and want to be able to display them vertically like so:
a d
b e
c f
def main():
letters = ["a", "b", "c", "d","e", "f"]
for i in letters:
print(i)
this code ...
0
votes
2answers
32 views
python: match and group sets of similar strings in a loop
I am trying to match and group similar strings from a list but I'm not sure how to approach this.
I have the following list:
tablenames =[
'SCS_q104',
...
0
votes
1answer
35 views
How to extract a word from a text given a position index?
Given a text like this:
s = "Lorem ipsum dolor sit amet"
How can I extract any word from it given the position index? For example, if pos is 6 or 8, the result should be "ipsum". If pos is 18, 19, ...
1
vote
1answer
26 views
find a keyword in a string with python and regex
I would like to find a keyword in a string that can be at the begining, the end, or anywhere in the string.
I started with something like that:
import re
my_keyword = "in ocean"
regex = ...
0
votes
2answers
37 views
invalid literal for int() error / when loops for humongous numbers [duplicate]
Continuing on with weeding out my misconceptions of Python fundamentals while trying to solve math problems. There are already working solutions for these floating around out there, I just want to see ...
0
votes
1answer
11 views
Returning binary data with django HttpResponse
I'm trying to get Django's HttpResponse to return binary data without much success. I've been trying different methods for a while now, but without success.
Encoding the string to ASCII works as long ...
0
votes
1answer
21 views
How to I change data-type of pandas data frame to string with a defined format
I'm starting to tear my hair out with this - so I hope someone can help. I have a pandas DataFrame that was created from an Excel spreadsheet using openpyxl. The resulting DataFrame looks like:
print ...
3
votes
2answers
86 views
What is a good way to store strings in Python?
I am building a conversation bot in Python. While I would like to generate as much text as possible from scratch, I still need a way to catalog and store a bunch of dialog fragment strings. Ideally I ...
0
votes
1answer
43 views
Error in Python and network X - TypeError: string indices must be integers, not str
I'm pretty new to coding, and am still exploring the endless joys of using Python. Please ask for any more info if you need it.
G is a networkx graph, such that:
G = ...
2
votes
0answers
34 views
grouping of strings with 1 mismatch
I have a set of DNA sequences and I would like to group them i.e clustering based on similarity. The file looks like
ATGCATGCATGCATGC
ATGCATGCATGCATGC
ATGCATGCATGCATGC
ATGCATGCATGCATGT
...
1
vote
1answer
37 views
python return duplicates in list
How do I find list of duplicates from list of strings?
clean_up function is given
def clean_up(s):
""" (str) -> str
Return a new string based on s in which all letters have been
converted to ...
0
votes
3answers
36 views
Conditioning on Regex,Python
i have several strings from which i need to extract the block numbers. The block numbers are of the format type "3rd block" , "pine block" ,"block 2" and "block no 4". Please note that is just the ...
0
votes
2answers
27 views
How to split a string containing digits and characters
I want to split a long string (containing digits and characters in it without any space) in to different substrings in Python?
>>> s = "abc123cde4567"
after split will get
['abc', '123', ...
-1
votes
2answers
67 views
how does str.split() divide a string?
line = (' 1.')
print(line.split(), len(line.split()))
This gives
['1.'] 1
But if I do
for value in line.split():
val = value
print(val, len(val))
I get
1. 2
Inspecting val gives ...
2
votes
2answers
40 views
Natural sort of a list of lists based on an alphanumeric string within sub-list?
Clear as mud, aye? I'll start with an example...
my_list = [[4,'A4, A23, A3, A6', 'Description 1', 'Property 1'],
[4,'B3, B35, B10, B22', 'Description 2', 'Property 2'],
...
-2
votes
1answer
37 views
Cannot concatenate 'str' and 'Nontype' objects error despite all arguments being pure string
I'm writing this python program and I'm getting this really confusing error in random. Here's part of my script:
Part of code in ai.py (starting at line #133)
elif (config.var0 < config.var1): ...
0
votes
4answers
42 views
Convert string in python to nd-array [duplicate]
Below is the data response from a call the the Yahoo! Finance API, the data is there, but it is a giant string. Any bright ideas of how to convert this to an array with Date, Open, High, Low, Close, ...
1
vote
2answers
29 views
How to lowercase a python dataframe string column if it has missing values?
The following code does not work.
import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['x'])
xLower = df["x"].map(lambda x: x.lower())
How should I tweak it to ...
0
votes
6answers
83 views
String equivalent of +=
Is there an equivalent of += for a string?
ie:
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += ...
0
votes
2answers
32 views
Making end=“ ” and sep=“ ” take variables
This is what I want it to be:
title = ['12', 'Years', 'a', 'Slave']
def join(x,y):
for x in title:
print(x,sep="y",end="")
join(title,-*-)
But I want it to see y as what is assigned to it ...
1
vote
4answers
53 views
find if string is a path
I am working in python. my problem is I have several strings and I have to detect which part of them look like a path and then normalize the ones that are actual paths.
e.g. I have several different ...
0
votes
4answers
41 views
Creating a dictionary with a list of names
I have this list of names: [Frank, Sam, Kevin, Jack]
Is it possible to create a dictionary using the names in the list to create something like this?
'Frank' : {'Sam': 0, 'Kevin': 0, 'Jack': 0},
...
0
votes
3answers
46 views
Sorting string into identical words
word = "help"
scrambled = ['p','e','h','l']
how would I arranged scrambled to be the same order as word? so pehl into help.
edit 1:
this is for a hangman game, so it would go:
guess 1:
input = "p"
...
-1
votes
1answer
27 views
Determine if the string contains any currency sign?
How can I find out if some string contains any currency sign? Say, I need a function that returns 1 if a string contains any currency sign(USD,GBP,RUR,etc) and 0 - otherwise
321->0
$32->1
...
1
vote
1answer
34 views
Efficient search in list of tuples
I want to search on a list and if find get its complement
E.g.:
l = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]
get_adjunct('1')
output
# u'a'
I know this way:
def ...
0
votes
2answers
55 views
Taking Linux Command as Raw String in Python
)I have confirmed my Linux command works in the terminal, however when I try to call it from python it breaks.
The command is a bit long and has lots of single quotes, so I wrapped it around three ...