so here is my relativly simple code:
#app.route("/[<string:pfade>]")
def testaufruf(pfade):
s=list(pfade)
part = [i for i,x in enumerate(s) if x=="$"]
print(part)
s[part]="\\"
print(part)
My problem is I want to pass something like 127.0.0.1:5000/[Test$path1]
now I take this Test$path1 make it an list and want to replace every $ with an \
These lines work:
s=list(pfade)
part = [i for i,x in enumerate(s) if x=="$"]
print(part)
They return me the place where the $ is located but the second part to replace the $ does not work. I did search a lot but couldnt find a solution to this problem.
Thanks for help in advance.
Strings have a replace method:
part = pfade.replace('$', '\\')
Note the \ is repeated for escaping.
this line is gonna return a list of integers
part = [i for i,x in enumerate(s) if x=="$"]
and you're simply trying to index s with a list, you're facing the following error
TypeError: list indices must be integers or slices, not list.
to solve this:
parts = [i for i,x in enumerate(s) if x=="$"]
for part in parts:
s[part] = '\\'
print(s)
So it was a pretty simple fix:
instead of using part = [i for i,x in enumerate(s) if x=="$"]
I just used: part = s.index("$", 0)
than s[part] = "\\" replaces the $ with "\"
Related
I have the following list
l=['web','python']
and the following string
st='python, C, something, find'
I want to check if any element in the list is in the string
I tried using
any(x in l for x in st)
however it gives false
seems python can't recognize the element in the string, is there a way to check elements from list to a string if there is a match. i did it successfully using a for a loop and splitting the string to a list however that is not efficient with the real data as it contain a long lists and strings. need something efficient.
thanks
You would first need to split the string, or else you will be iterating over the individual characters.
Try this:
l=['web','python']
st='python, C, something, find'
any([x in l for x in st.split(',')]) # True
But this isn't the most efficient. For better performance, you could take a look into using a trie.
If your would like to check if any element in the list is in the string
then your code should be
any(x in st for x in l)
You can use this method
word_list = ['web','python']
string = 'python, C, something, find'
exist = filter(lambda x : x in string , word_list)
print(list(exist))
output:
['python']
You were close. How about:
any(x in l for x in st.replace(',', '').split())
which returns:
True
A different approach:
import re
re.search(r'\b(' + '|'.join(l) + r')\b', st)
The search will return None if there's no match and the match if there is one. You can use it like:
if re.search(r'\b(' + '|'.join(l) + r')\b', st):
print(f'there was a match: {t.groups()}')
else:
print('no match')
Beginner here. I'm having problems with this task: accum("hello") should return "H-Ee-Lll-Llll-Ooooo". But what I get with my code is "H-Ee-Lll- Lll -Ooooo". It doesn't work for double characters. Is this because the iteration variable in "for i in s" "skips" over double "i's" or something? And do you have an idea how I can fix this? I'm not striving for elegant code or something, my goal atm is to try and make easily readable lines for myself :)
Thank you!
(Sorry if this is something basic, I didn't really know what to search for!)
def accum(s):
s_list = []
s = [ele for ele in s]
for i in s:
sum_ind = ((s.index(i)) + 1) * i
s_list.append(sum_ind)
s_list = [e.capitalize() for e in s_list]
s_list = '-'.join(s_list)
return s_list
Here's a way to do:
def accum(stri):
p = []
for i, s in enumerate(stri, 1):
p.append((s*i).capitalize())
return '-'.join(p)
accum('hello')
'H-Ee-Lll-Llll-Ooooo'
Take a quick read about: enumerate
I think you could solve this easily with enumerate:
def accum(s):
r = []
for i, letter in enumerate(s):
r.append(letter.upper() + (letter*i).lower())
return '-'.join(r)
Here is one way:
def accum(s):
return "-".join( (c*i).capitalize() for i,c in enumerate(s,1) )
yields:
'H-Ee-Lll-Llll-Ooooo'
As mentioned in many comments, we can give a short explanation of working of enumerate here.
As per your requirement, given a letter from a string, you find its index (position). Then you first make the caps of letter and glue it with index-times small letters.
So you need a counter which keeps track of the position of letter, so we can do something like this (A DUMMY, SLOW EXAMPLE):
def accum(word):
ans = ""
for index in range(len(word)):
letter = word[index]
ans += letter.upper() + index*letter + "-"
else:
word = word[:-1] #Remove trailing '-'
return word
BUT THIS FUNCTION IS EXTREMELY SLOW. BECAUSE IT USES SIMPLE STRING ADDITION AND NOT OTHER PROPER METHOD.
That's why people ask you to use enumerate. In short it keeps track of your indices.
for index, name in enumerate(["John", "Lex", "Vui"]):
print(name, "is found at", index)
That's it !
{Im not writing the answer you wanted, as almost everyone provided the best answer, they could, my aim was to explain you the use of enumerate and other slow methods for your problem}
What is the best way to use Regex to extract and transform one statement to another?
Specifically, I have implemented the below to find and extract a sudent number from a block of text and transform it as follows: AB123CD to AB-123-CD
Right now, this is implemented as 3 statements as follows:
gg['student_num'] = gg['student_test'].str.extract('(\d{2})\w{3}\d{2}') + \
'-' + gg['student_num'].str.extract('\d{2}(\w{3})\d{2}') + \
'-' + gg['student_test'].str.extract('\d{2}\w{3}(\d{2})')
It doesn't feel right to me that I would need to have three statements -
one for each group - concatenated together below (or even more if this was more complicated) and wondered if there was a better way to find and transform some text?
You could get list of segments using regexp and then join them this way:
'-'.join(re.search(r'(\d{2})(\w{3})(\d{2})', string).groups())
You could get AttributeError if string doesn't contain needed pattern (re.search() returns None), so you might want to wrap this expression in try...except block.
This is not regex, but it is quick and concise:
s = "AB123CD"
first = [i for i, a in enumerate(s) if a.isdigit()][0]
second = [i for i, a in enumerate(s) if a.isdigit()][-1]
new_form = s[:first]+"-"+s[first:second+1]+"-"+s[second+1:]
Output:
AB-123-CD
Alternative regex solution:
letters = re.findall("[a-zA-Z]+", s)
numbers = re.findall("[0-9]+", s)
letters.insert(1, numbers[0])
final = '-'.join(letters)
print(final)
Output:
AB-123-CD
Try this. Hope that helps
>>> import re
>>> s = r'ABC123DEF'
>>> n = re.search(r'\d+',s).group()
>>> f = re.findall(r'[A-Za-z]+',s)
>>> new_s = f[0]+"-"+n+"-"+f[1]
>>> new_s
Output:
'ABC-123-DEF'
I'm trying to make a function, f(x), that would add a "-" between each letter:
For example:
f("James")
should output as:
J-a-m-e-s-
I would love it if you could use simple python functions as I am new to programming. Thanks in advance. Also, please use the "for" function because it is what I'm trying to learn.
Edit:
yes, I do want the "-" after the "s".
Can I try like this:
>>> def f(n):
... return '-'.join(n)
...
>>> f('james')
'j-a-m-e-s'
>>>
Not really sure if you require the last 'hyphen'.
Edit:
Even if you want suffixed '-', then can do like
def f(n):
return '-'.join(n) + '-'
As being learner, it is important to understand for your that "better to concat more than two strings in python" would be using str.join(iterable), whereas + operator is fine to append one string with another.
Please read following posts to explore further:
Any reason not to use + to concatenate two strings?
which is better to concat string in python?
How slow is Python's string concatenation vs. str.join?
Also, please use the "for" function because it is what I'm trying to learn
>>> def f(s):
m = s[0]
for i in s[1:]:
m += '-' + i
return m
>>> f("James")
'J-a-m-e-s'
m = s[0] character at the index 0 is assigned to the variable m
for i in s[1:]: iterate from the second character and
m += '-' + i append - + char to the variable m
Finally return the value of variable m
If you want - at the last then you could do like this.
>>> def f(s):
m = ""
for i in s:
m += i + '-'
return m
>>> f("James")
'J-a-m-e-s-'
text_list = [c+"-" for c in text]
text_strung = "".join(text_list)
As a function, takes a string as input.
def dashify(input):
output = ""
for ch in input:
output = output + ch + "-"
return output
Given you asked for a solution that uses for and a final -, simply iterate over the message and add the character and '-' to an intermediate list, then join it up. This avoids the use of string concatenations:
>>> def f(message)
l = []
for c in message:
l.append(c)
l.append('-')
return "".join(l)
>>> print(f('James'))
J-a-m-e-s-
I'm sorry, but I just have to take Alexander Ravikovich's answer a step further:
f = lambda text: "".join([c+"-" for c in text])
print(f('James')) # J-a-m-e-s-
It is never too early to learn about list comprehension.
"".join(a_list) is self-explanatory: glueing elements of a list together with a string (empty string in this example).
lambda... well that's just a way to define a function in a line. Think
square = lambda x: x**2
square(2) # returns 4
square(3) # returns 9
Python is fun, it's not {enter-a-boring-programming-language-here}.
I am having trouble figuring out the following:
Suppose I have a list of strings
strings = ["and","the","woah"]
I want the output to be a list of strings where the ith position of every string becomes a new string item in the array like so
["atw","nho","dea","h"]
I am playing with the following list comprehension
u = [[]]*4
c = [u[i].append(stuff[i]) for i in range(0,4) for stuff in strings]
but its not working out. Can anyone help? I know you can use other tools to accomplish this, but i am particularly interested in making this happen with for loops and list comprehensions. This may be asking a lot, Let me know if I am.
Using just list comprehensions and for loops you can:
strings = ["and","the","woah"]
#Get a null set to be filled in
new = ["" for x in range(max([len(m) for m in strings]))]
#Cycle through new list
for index,item in enumerate(new):
for w in strings:
try:
item += w[index]
new[index] = item
except IndexError,err:
pass
print new
My idea would be to use itertools.izip_longest and a list comprehension.
>>> from itertools import izip_longest
>>> strings = ["and","the","woah"]
>>> [''.join(x) for x in izip_longest(*strings, fillvalue='')]
['atw', 'nho', 'dea', 'h']
Try
array = ["and","the","woah"]
array1 = []
longest_item = 0
for i in range(0,3): #length of array
if len(array[i]) > longest_item:
longest_item = len(array[i]) #find longest string
for i in range(0,longest_item):
str = ""
for i1 in range(0,3): #length of array
if len(array[i1]) < longest_item:
continue
str += array[i1][i:i+1]
array1.append(str)
I didn't actually try this code out, I just improvised it. Please leave a comment ASAP if you find a bug.