How can i make specific output using a strip function? - python

I am trying to remove some symbols from output, but it does not work. I've tried many ways to do this, also i searched many similar questions, but i still don't have an answer. Here is the code:
cur.execute("SELECT * FROM test;")
all = cur.fetchone()
str1 = str(all)
str2 = str1.strip("()")
str3 = str2.strip(",")
str4 = str3.strip("()")
str5 = str4.strip("''")
str6 = str5.strip("', '")
print(str6)
The output is:
f', 'f
Instead of:
f f
Sorry for bad code. Thanks for help

Maybe you are looking for .replace() function
string = "f', 'f"
string = string.replace("', '", " ")
print(string)
Outputs:
f f

Not entirely sure what you are asking. Strip pulls characters off of either side of the string if they exist. You may be looking for the .replace() method instead.

the strip()method only removes from left or right part of the string, not in the middle of the string. For that you would need to use replace()instead. Note that the way you seem to approach this wouldn't result in good code and isn't the way you would handle a db response.
I would rather recommend the following: The db call returns the result in a tuple datatype. In case you want to output the result from each individual item in the db call, i would rather recommend iterating through the result and converting each item to str rather than converting the entire result tuple to a string and replacing characters. The below would produce the output you are looking for and is a more correct way of going about it.
db_result = ('f', 'f')
for item in db_result:
print(str(item), end=" ")
print()

Related

TypeError: 'int' object is not iterable. When iterating over each string in string data

good day,
My objective is to use .lower() for converting each string in the text data into the lower case. I tried to use .count() with a one-liner iteration. However, I get the following error:
TypeError: 'int' object is not iterable
Here is my code:
# Iterating over the strings in the data. The data is called text
text_lowercase = ''.join((string.lower().strip() for string in text.count(0,)))
I want to use the one-liner iteration and do this.
Help would be truly appreciated. Cheers!
text.count returns an integer. You try to iterate over it:
for string in text.count(0,)
but since it returns an integer, there is no in (it is not iterable). This is what the error message is telling you.
In the future, to better identify the source of an error, try to break up one-liners into multiple lines. This will give you better feedback on what part of your operation is failing.
There's a couple of issues to point out here:
text_lowercase = ''.join((string.lower().strip() for string in text.count(0,)))
Naming the temporary variable string is a bad idea, as this looks a lot like the type name. Something like s is more common and readable.
Or perhaps word because that's what you are after it seems. This is the second problem, your approach seems to break down the string in characters, but from the comments it appears you'd like to operate on words? (your use of strip also suggests this)
You're joining on '', which results in all the parts of the string being joined with no space between them.
As others point out, count returns an integer, but you want to operate on the actual string. You indicated you only tried count to iterate and that's not needed in Python like it is in many other languages.
Putting it together for words:
text_lowercase = ' '.join([w.lower() for w in text.split(' ')])
Or if you're after characters:
text_lowercase = ''.join([ch.lower() for ch in text])
But then you could just:
text_lowercase = text.lower()
Perhaps you like words, but want to get rid of excess spaces?
text_lowercase = ' '.join([w.lower() for w in text.split(' ') if w != ''])
Or in shorthand:
text_lowercase = ' '.join([w.lower() for w in text.split(' ') if w])
The exception you get is because the count() returns an int and then you try to iterate over that int. I think you should remove the count and you might be good to go (depending on how text looks like)
If you want to have a function that just lower cases the instances of string inside your text, maybe you can use something like this:
def lowercase_instance(text, string):
return string.lower().join(text.split(string))
Now, if you have a list of texts then you can do something like this:
lowercase_texts = [lowercase_instance(text, string) for text in texts]
hopefully this helps!

How to replace user's input?

I'm trying to make a Text to Binary converter script. Here's what I've got..
userInput = input()
a = ('00000001')
b = ('00000010')
#...Here I have every remaining letter translated in binary.
z = ('00011010')
So let's say the user types the word "Tree", I want to convert every letter in binary and display it. I hope you can understand what I'm trying to do here.
PS. I'm a bit newbie! :)
The way you have attempted to solve the problem isn't ideal. You've backed yourself into a corner by assigning the binary values to variables.
With variables, you are going to have to use eval() to dynamically get their value:
result = ' '.join((eval(character)) for character in myString)
Be advised however, the general consensus regarding the use of eval() and similar functions is don't. A much better solution would be to use a dictionary to map the binary values, instead of using variables:
characters = { "a" : '00000001', "b" :'00000010' } #etc
result = ' '.join(characters[character] for character in myString)
The ideal solution however, would be to use the built-in ord() function:
result = ' '.join(format(ord(character), 'b') for character in myString)
Check the ord function:
userinput = input()
binaries = [ord(letter) for letter in userinput]
cheeky one-liner that prints each character on a new line with label
[print(val, "= ", format(ord(val), 'b')) for val in input()]
#this returns a list of "None" for each print statement
similarly cheeky one-liner to print with arbitrary seperator specified by print's sep value:
print(*[str(val) + "= "+str(format(ord(val), 'b')) for val in input()], sep = ' ')
Copy and paste into your favorite interpreter :)

a mistake I keep having with for loops and return statements

I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it.
I will give you an example of this happening with a code I just wrote:
def remove_exclamation(string):
string.split(' ')
for i in string:
i.split()
for char in i:
if char == '!':
del char
''.join(i)
' '.join(string)
return string
For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:
>>>remove_exclamation('This is an example!')
'This is an example'
But instead I get this:
>>>remove_exclamation('This is an example!')
'This is an example!'
The function is not removing the exclamation in the output, and is not doing what I intended for it to day.
How can I keep avoiding this when I make for loops, nested for loops etc?
You write your code and formulate your question as if it was possible to modify strings in Python. It is not possible.
Strings are immutable. All functions which operate on strings return new strings. They do not modify existing strings.
This returns a list of strings, but you are not using the result:
string.split(' ')
This also:
i.split()
This deletes the variable named char. It does not affect the char itself:
del char
This creates a new string which you do not use:
''.join(i)
This also:
' '.join(string)
All in all, almost every line of the code is wrong.
You probably wanted to do this:
def remove_exclamation(string):
words = string.split(' ')
rtn_words = []
for word in words:
word_without_exclamation = ''.join(ch for ch in word if ch != '!')
rtn_words.append(word_without_exclamation)
return ' '.join(rtn_words)
But in the end, this does the same thing:
def remove_exclamation(string):
return string.replace('!', '')
Without clearly knowing the intentions of your function and what you are attempting to do. I have an alternative to the answer that zvone gave.
This option is to remove any characters that you have not defined in an allowed characters list:
characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
test_string = "This is an example!"
test_string = ''.join(list(filter(lambda x: x in characters, test_string)))
print(test_string)
This outputs:
This is an example
Note, this is the Python 3 version.
Python 2, you do not need the ''.join(list())
Doing it this way would allow you to define any character that you do not want present in your string, and it will remove them.
You can even do the reverse:
ignore_characters= "!"
test_string = "This is an example!"
test_string = ''.join(list(filter(lambda x: x not in ignore_characters, test_string)))
print(test_string)
Strings are immutable in Python. And you cannot change them. You can however, re-assign there values.
That is where your problem lies. You never reassign the value of your strings, when you call .split() on them.
But there are also others errors in your program such as:
Your indention
The fact that your just returning the string thats passed into the function
Your use of the del statement
etc.
Instead, create a new string by iterating through the old one and filtering out the character(s) you do not want, via list comprehension and ''.join().
def remove_exclamation(string):
return ''.join([char for char in string if char != '!'])
But as #Moses has already said in the comments, why not just use str.replace()?:
string = string.replace('!', '')
def remove_exclamation(string):
#you think you are splitting string into tokens
#but you are not assigning the split anywhere...
string.split(' ')
#and here you are cycling through individual _chars_ in string which was not affected by the split above ;-)
for i in string:
#and now you are splitting a 1-char string and again not assigning it.
i.split()
And string is still your input param, which I assume is of type str. And immutable.
On top of which, if you were import/using the string module, you would be shadowing it
A big part of your confusion is knowing when the methods mutate the objects and when they return a new object. In the case of strings, they never mutate, you need to assign the results to a new variable.
On a list however, and the join() somewhere makes me think you want to use a list, then methods generally change the object in place.
Anyway, on to your question:
def remove_exclamation(inputstring, to_remove="!"):
return "".join([c for c in inputstring if c != to_remove])
print (remove_exclamation('This is an example!'))
output:
This is an example

How do I strip a string given a list of unwanted characters? Python

Is there a way to pass in a list instead of a char to str.strip() in python? I have been doing it this way:
unwanted = [c for c in '!##$%^&*(FGHJKmn']
s = 'FFFFoFob*&%ar**^'
for u in unwanted:
s = s.strip(u)
print s
Desired output, this output is correct but there should be some sort of a more elegant way than how i'm coding it above:
oFob*&%ar
Strip and friends take a string representing a set of characters, so you can skip the loop:
>>> s = 'FFFFoFob*&%ar**^'
>>> s.strip('!##$%^&*(FGHJKmn')
'oFob*&%ar'
(the downside of this is that things like fn.rstrip(".png") seems to work for many filenames, but doesn't really work)
Since, you are looking to not delete elements from the middle, you can just use.
>>> 'FFFFoFob*&%ar**^'.strip('!##$%^&*(FGHJKmn')
'oFob*&%ar'
Otherwise, Use str.translate().
>>> 'FFFFoFob*&%ar**^'.translate(None, '!##$%^&*(FGHJKmn')
'oobar'

String concatenation produces incorrect output in Python?

I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
Does this do what you want?
>>> filenames=["file1","FILE2","file3","fiLe4"]
>>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames))
>>> c
'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'
Using a string.join is a much better way to add a common delimiter to a list of items. It negates the need to have to check for being on the last item before adding the delimiter, or in your case attempting to strip off the last one added.
Also, you may want to look into List Comprehensions
It looks like you might be trying to use python to write an R script, which can be a quick solution if you don't know how to do it in R. But in this case the R-only solution is actually rather simple:
R> filenames= c("file1","FILE2","file3","fiLe4")
R> suffixes <- paste(".", tolower(filenames), sep="")
R> suffixes
[1] ".file1" ".file2" ".file3" ".file4"
R>
What's going on is that this slicing returns an empty string
filestring=filestring[-1:-4]
Because the end is before the begin. Try the following on the command line:
>>> a = "hello world"
>>> a[-1:-4]
''
The solution is to instead do
filestring=filestring[:-4]+filestring[-1:]
But I think what you actually wanted was to just drop the last three characters.
filestring=filestring[:-3]
The better solution is to use the join method of strings as sberry2A suggested

Categories

Resources