how to add apostrophe in a string? [duplicate] - python

This question already has answers here:
How to convert list into string with quotes in python
(5 answers)
Join a list of strings in python and wrap each string in quotation marks
(9 answers)
Closed 2 years ago.
string='98.87,100.91,22.12'
print(string)
98.87,100.91,22.12
then I want to add apostrophe like this
'98.87','100.91','22.12'
how can I do this?
thanks
Thanks all
I know I can use "'98.87'" to print
'98.87'
But actually I want to add apostrophe by code
Because I will get string from
string = request['string']
then I want to let this string in SQL query
SELECT * FROM table WHERE str IN ({}).format(string)
I wnat to result become to
SELECT * FROM table WHERE str IN ('98.87','100.91','22.12')

You can use double quotes to define your string and the single quotes inside it or use backslash ('\')
string_value = "'98.87','100.91','22.12'"
Or
string_value = '\'98.87\',\'100.91\',\'22.12\''
To create a new string with the apostrophes you could do:
string = '98.87,100.91,22.12'
string_list = [f"'{value}'" for value in string.split(',')]
separator = ','
string_with_apostrophe = separator.join(string_list)

numbers=[98.87,100.91,22.12]
mylist= []
for num in numbers:
a= "'%s'" %(num)
mylist.append(a)
mylist2=",".join(mylist)
print(mylist2)

This should work with any numbers:
>>> a = '98.87,100.91,22.12'
>>> nums = a.split(',')
>>> nums
['98.87', '100.91', '22.12']
>>> result = str(nums).replace('[','').replace(']','')
>>> result
"'98.87', '100.91', '22.12'"
>>>
You may easily clean up spaces using replace(), which I did not for the sake of simplicity.

Related

how to strip a set of characters from a string in a program in python [duplicate]

This question already has answers here:
Python strip() multiple characters?
(7 answers)
Closed 11 months ago.
here is my code:
string = input("Enter a string:")
print(string)
characters = input("Enter the characters you would like to make disappear:")
print(characters)
print(string.replace("characters"," "))
I need to display variable string without the entered characters in variable characters
You need to iterate over the characters, and replace each one by one
Example
for ch in "characters":
string.replace(ch, "")
Example using re to remove all vowels in your string:
>>> import re
>>> characters_to_remove = "aeiouy"
>>> my_string = "my string"
>>> re.sub(f"[{characters_to_remove}]", "", my_string)
'm strng'

How to delete the following characters in a string with python? [duplicate]

This question already has answers here:
How do I remove a substring from the end of a string?
(23 answers)
Closed 1 year ago.
How can I delete the following characters in a string: '.SW'. Characters to remove are '.SW' in the following example:
stock = 'RS2K.SW'
original_string = stock
characters_to_remove = ".SW"
new_string = original_string
for character in characters_to_remove:
new_string = new_string.replace(character, "")
stocketf = new_string
print (stocketf)
Result should be:
RS2K
My actual wrong result is:
R2K
There are a few ways to choose from as the existing answers demonstrate. Another way, if these characters always come at the end, could be to just split your string on the '.' character and keep the first section:
stock = 'RS2K.SW'
new_string = stock.split(.)[0]
In this case, it looks like that you could just remove the last three characters.
my_str = my_str[:-3]
Otherwise, I would suggest using Regex
In this case this should be a valid solution for your answer:
stock = 'RS2K.SW'
original_string = stock
characters_to_remove = ".SW"
new_string =
stock[:original_string.index(characters_to_remove)]
print(new_string)

How to replace backslash with my comma in a list [duplicate]

This question already has answers here:
Split string using a newline delimiter with Python [duplicate]
(7 answers)
Closed 3 years ago.
I am making a program that will print strings and turn them into a list. My problem is when I print it I get backslashes (\) instead of , which I can't use. Any help on replacing it?
Here is what I tried:
def Convert(string):
li = list(string.split('\\'))
return li
Full Code:
def Convert(string):
li = list(string.split('\\'))
return li
str1 = ("""Kellokolme1#gmail.com
stacexbeatz500#gmail.com
hiimjose789#gmail.com
AlexSaberOfficial#gmail.com
ferncuevas15#gmail.com
royodero45#gmail.com
youthdombeats#gmail.com
chris.rhames5#gmail.com
bloombeats01#gmail.com
16premebeats#gmail.com
TmanBeatz.Info#Gmail.com
alexbuus65#gmail.com
Armotunez#gmail.com
aydbeats#gmail.com
iblouir79#hotmail.com
contact#curtbain.com
aminebeats7#gmail.com
markusrovelstad#gmail.com
eddie#lilsoy.com
t-way974#hotmail.com
prodbykamikaze#gmail.com
matteobeats08#gmail.com
markusrovelstad#gmail.com
grandmbeats#gmail.com""")
print(Convert(str1))
I would like to see the commas but instead i get this:
['Kellokolme1#gmail.com\nstacexbeatz500#gmail.com\nhiimjose789#gmail.com\nAlexSaberOfficial#gmail.com\nferncuevas15#gmail.com\nroyodero45#gmail.com\nyouthdombeats#gmail.com\nchris.rhames5#gmail.com\nbloombeats01#gmail.com\n16premebeats#gmail.com\nTmanBeatz.Info#Gmail.com\nalexbuus65#gmail.com\nArmotunez#gmail.com\naydbeats#gmail.com\niblouir79#hotmail.com\ncontact#curtbain.com\naminebeats7#gmail.com\nmarkusrovelstad#gmail.com\neddie#lilsoy.com\nt-way974#hotmail.com\nprodbykamikaze#gmail.com\nmatteobeats08#gmail.com\nmarkusrovelstad#gmail.com\ngrandmbeats#gmail.com']
You need to split on \n (newline):
def Convert(string):
li = list(string.split('\n'))
return li
Just use str.splitlines on your string:
str1 = """Kellokolme1#gmail.com
stacexbeatz500#gmail.com
hiimjose789#gmail.com
"""
str1.splitlines()
# ['Kellokolme1#gmail.com', 'stacexbeatz500#gmail.com', 'hiimjose789#gmail.com']

Python: Keeping whitespace at the beginning of a string [duplicate]

This question already has answers here:
Grab a line's whitespace/indention with Python
(6 answers)
Closed 5 years ago.
I Have a string that looks like this:
old_string = ' Some_text'
And I want to write a new string, but I would like to keep the same white-space at the beginning.
Is there a way in Python that I can keep this white-space?
The white-space could contain spaces or tabs, but the exact number of tabs or spaces is unknown.
I think this could be done using regex but I'm not sure if there is a way. And since the text in the string is not always the same I can't use
new_string = old_string.replace('Some_text','new_text')
any thoughts would be more than welcome.
You can do:
new_string = old_string[:-len(old_string.lstrip())] + 'new text'
Or if you prefer str.format:
new_string = '{}new text'.format(old_string[:-len(old_string.lstrip())])
Count how many characters get removed when you use lstrip;
str = ' Some_text'
whitespace = len(str) - len(str.lstrip())
print(whitespace)
Outputs;
6
You can use itertools.takewhile() to get the leading whitespace characters:
>>> from itertools import takewhile
>>> old_string = ' Some_text'
>>> whitespace = list(takewhile(str.isspace, old_string))
>>> "".join(whitespace)
' '
>>> len(whitespace)
6
To get the rest of the string you could use itertools.dropwhile():
>>> "".join(dropwhile(str.isspace, old_string))
'Some_text'

how to change a character by its position in a string python [duplicate]

This question already has answers here:
Changing one character in a string
(15 answers)
Closed 8 years ago.
Im trying to make a Hangman game and I need to change certain characters in a string.
Eg: '-----', I want to change the third dash in this string, with a letter. This would need to work with a word of any length, any help would be greatly appreciated
Strings are immutable, make it a list and then replace the character, then turn it back to a string like so:
s = '-----'
s = list(s)
s[2] = 'a'
s = ''.join(s)
String = list(String)
String[0] = "x"
String = str(String)
Will also work. I am not sure which one (the one with .join and the one without) is more efficient
You can do it using slicing ,
>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>>

Categories