How to convert single element tuple into string? - python

I have this code:
import nltk
import pypyodbc
text = raw_input()
token = nltk.word_tokenize(text) //return a list value
def search(self, lists):
if not self.connected:
self.connect()
for word in lists:
self.cur.execute('SELECT Ybanag FROM Words WHERE English IN (%s)' % (','.join('?'*len(lists))), lists)
result = self.cur.fetchall()
return result
wherein the output is a list of single element tuple (ex. I enter we all there):
[('tore',), ('ngaming',), ('sittam',)] (translate the input into mother tongue language). I want that the output will be converted into string to eliminate the [],(),'',' symbols. How to convert it into string?

You have to use str.join method.
>>> a = [('tore',), ('ngaming',), ('sittam',)]
>>> " ".join([x[0] for x in a])
'tore ngaming sittam'

I would just use a for loop. You can loop through the list of tuples and add each element to an empty string variable
x = [('tore'), ('ngaming'), ('sittam')]
z = ""
for i in x:
z = z + i + " "
print z
After seeing Lafada's answer, I realized that list comprehension and str.join is the best option. Though his answer is better, this is basically what his answer does, just done more manually.

Related

how to convert a string of numbers to a list and square up ** and get it printed out back as string

Given a string of the form "3,9,13,4,42". It is necessary to convert it into a list and calculate its square for each element. Then join the squares of those elements back into a string and print it in the console.
input
input:
string = "3,9,13,4,42"
output:
string= "9,81,169,16,1764"
Managed to get it squared up, tried converting it to list fist, but when checked type at the end, always somehow getting it as tuple.
Ty for help.
Hope this answers your question.
# input
str_numbers = "3,9,13,4,42"
# string to list
str_number_list = str_numbers.split(",")
# list of strings to list of ints
number_list = [int(x) for x in str_number_list]
# square all numbers
squared_numbers = [x ** 2 for x in number_list]
# squared numbers back to a list of strings
str_squared_numbers = [str(x) for x in squared_numbers]
# joing the list items into one string
result = ",".join(str_squared_numbers)
# print it out
print(f"Input: {str_numbers}")
print(f"Output: {result}")
// First Approach
string = "3,9,13,4,42"
array = string.split(',')
array = map(lambda x: str(int(x)**2),array)
result = ','.join(list(array))
print(result) // "9,81,169,16,1764"
// Second Approach
string = "3,9,13,4,42"
result = ','.join([str(int(x)**2) for x in string.split(',')])
print(result) // '9,81,169,16,1764'
Can do with split + join,
In [1]: ','.join(map(lambda x: str(int(x)**2), s.split(',')))
Out[1]: '9,81,169,16,1764'
You have so many ways to solve the problem. I'll show you a few by degree of complexity of understanding. Each way has a different computational complexity, but for such a problem we will not go into detail.
N.B.: Casting should be done at float and not at int because it is not certain a priori that there are integers in the input string.
Using List Comprehension
List comprehension offers a shorter syntax when you want to create a
new list based on the values of an existing list.
I divide the code into 3 steps just for greater understanding:
input_string = "3,9,13,4,42"
num_list = [float(x) for x in input_string.split(",")] # split list by comma and cast each element to float
squares_list = [x**2 for x in num_list] # make square of each number in list
output_string = [str(x) for x in squares_list] # cast to string each element in list
print(output_string)
Using join, map and lambda
The join() method takes all items in an iterable and joins them into
one string.
The map() function applies a given function to each item of an
iterable (list, tuple etc.) and returns an iterator.
A Lambda Function is an anonymous function, that is, a function that
has not been assigned a name and is used to use the features of
functions but without having to define them.
output_string = ','.join(map(lambda x: str(float(x)**2), input_string.split(',')))
You are absolutely right assume-irrational-is-rational
string = "3,9,13,4,42"
def squares_string(string):
output = ",".join(tuple(map(lambda x: str(int(x)**2), "3,9,13,4,42".split(","))))
return output
output = squares_string(string)
print(output)
print(type(output))
Result:
9,81,169,16,1764
<class 'str'>

compare list elment to a string

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')

how not to replace certain characters in a string in python?

Let's say replace characters but not last "4" with "!" in a random string.
or replace characters but not middle "3" with "#" in a random string.
example 1:
input(hdasd1234)
output(!!!!!1234)
example 2:
input(asadfe455)
output(###dfe###)
x = str(input())
y = "!" * (len(x) - 4) + x[-4:]
print(x)
This code is not working.
For a very basic, direct solution, you can do this:
Example one:
string = input() #input automatically returns a string, so there's no need for str()
y = '!' * (len(string)-5) + string[4:]print (y) #remember to print y, not string because y is the modified version of your string
And example two
string = input()
y = "#" * 3 + string[3:6] + "#" * 3
print (y)
For a more flexible method to this approach, you should create a function. Assuming you are given the positions of where to change the string in a list, the string, and the specific marker to replace string[n] with, this should be fairly simple:
def replace_chars(string, positions, s):
new_string = []
for i in range(len(string)):
if i not in positions: #Checking if position, i, is not one of the marked positions
new_string.append(string[i])
else: #If it is a marked positions, append it with the marker, s, or more specifically '#'
new_string.append(s)
return ''.join(new_string) #Make the list a string
This could be written in a 1-2 lines long function with one line for loops but this formatting is better for readability. But if you were to do it in 1-2 lines, it would look like this:
def replace_chars(string, positions, s):
new_string = [string[i] if i not in positions else s for i in range(len(string))]
return ''.join(new_string)
The code is printing the value of x which is not modified.
Your code logic is creating a new variable y with the result and the x is unmodified.
However,you are printing the value of x which is the exact same input.
The logic seems to be working and the result is correct for the value of y.
Please check on that.
If any issues,please post the error log or the results.

What do these single quotes do at the beginning of line 2?

I found the following code in some random website explaining concatenating:
data_numb = input("Input Data, then press enter: ")
numb = ''.join(list(filter(str.isdigit, data_numb)))
print('(' + numb[:3] + ') ' + numb[3:6] + '-' + numb[6:])
and I was wondering what the single quotes do in the
numb = ''.join(
Any help is appreciated!
join(iterable) is a method from the str class.
Return a string which is the concatenation of the strings in iterable.
A TypeError will be raised if there are any non-string values in
iterable, including bytes objects. The separator between elements is
the string providing this method.
''.join(("Hello", "World")) will return 'HelloWorld'.
';'.join(("Hello", "World", "how", "are", "you")) will return 'Hello;World;how;are;you'.
join is very helpful if you need to add a delimiter between each element from a list (or any iterable) of strings.
It looks like nothing but if you do not use join, this kind of operation is often ugly to implement because of edge effects:
For a list or tuple of strings :
def join(list_strings, delimiter):
str_result = ''
for e in list_strings[:-1]:
str_result += e + delimiter
if list_strings:
str_result += list_strings[-1]
return str_result
For any iterable :
def join(iterable, delimiter):
iterator = iter(iterable)
str_result = ''
try:
str_result += next(iterator)
while True:
str_result += delimiter + next(iterator)
except StopIteration:
return str_result
Because join works on any iterable, you don't need to create a list from the filter result.
numb = ''.join(filter(str.isdigit, data_numb))
works as well
Join method is used to concatenate a string with any iterable object. In this example, the first string is an empty string, also represented by two single quotes, '' (don't confuse the single quotes with a single double quote).
The join() method of a string object concatenates it with another iterable provided. So, if the first string is an empty string, the resultant string is the concatenated output of the elements in the iterable.
What is its use:
It can be used to concatenate a list of strings. For example:
a = ['foo', 'bar']
b = ''.join(a)
print(b) # foobar
It can be used to concatenate strings. (Since a string is an iterable, as well)
a = "foobar"
b = ''.join(a)
print(b) # foobar
You can think of more use cases, but this is just a gist of it. You can also refer to the documentation here.

Print the first, second occurred character in a list

I working on a simple algorithm which prints the first character who occurred twice or more.
for eg:
string ='abcabc'
output = a
string = 'abccba'
output = c
string = 'abba'
output = b
what I have done is:
string = 'abcabc'
s = []
for x in string:
if x in s:
print(x)
break
else:
s.append(x)
output: a
But its time complexity is O(n^2), how can I do this in O(n)?
Change s = [] to s = set() (and obviously the corresponding append to add). in over set is O(1), unlike in over list which is sequential.
Alternately, with regular expressions (O(n^2), but rather fast and easy):
import re
match = re.search(r'(.).*\1', string)
if match:
print(match.group(1))
The regular expression (.).*\1 means "any character which we'll remember for later, any number of intervening characters, then the remembered character again". Since regexp is scanned left-to-right, it will find a in "abba" rather than b, as required.
Use dictionaries
string = 'abcabc'
s = {}
for x in string:
if x in s:
print(x)
break
else:
s[x] = 0
or use sets
string = 'abcabc'
s = set()
for x in string:
if x in s:
print(x)
break
else:
s.add(x)
both dictionaries and sets use indexing and search in O(1)

Categories

Resources