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

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)

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 only keep certain characters in a string [duplicate]

This question already has answers here:
Keeping only certain characters in a string using Python?
(3 answers)
Closed 1 year ago.
I'm just a beginner so this might be a stupid question but, I'm trying to remove every character from a string except the ones in a list
for example:
you have a string H][e,l}l.o1;4.I want only letters and numbers in the output.
It should look like this:
Hello14
Does anyone have any idea what needs to come behind the str1 = or any other methods?
This is what I tried so far:
def stringCleaner(s):
# initialize an empty string
str1 = " "
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
for x in range(len(s)):
if any((c in chars) for c in s):
str1=
return str1
It will be better to simply iterate over your input string and create a list of allowed characters and join() the list into a string again at the end.
def stringCleaner(s):
# initialize an empty list
str1 = []
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
for c in s:
if c in chars:
str1.append(c)
return ''.join(str1)
And then you should be able to see that its only a few short steps to get even better code such as the answer that #user1740577 has posted.
You can for any char in s check in chars list and .join() all of them if exist in chars list.
Try this:
def stringCleaner(s):
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
return ''.join(c for c in s if c in chars)
stringCleaner('H][e,l}l.o1;4.I')
# 'Hello14I'

how to add apostrophe in a string? [duplicate]

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.

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'

Removing all numeric characters in a string, python [duplicate]

This question already has answers here:
Removing numbers from string [closed]
(8 answers)
Closed 5 years ago.
Im looking to remove every single number in a string. More specifically, i'm looking to remove all numbers in the following codes string
Comp_String = "xxf1,aff242342"
how can one do this. (Obviously inside the code). I have found many answers to questions about removing the actual parts of the code that are letters but not numbers. Please explain aswell what your code is actually doing
You can find the answer here
Removing numbers from string
From this answer:
comp_string = "xxf1,aff242342"
new_string = ''.join([i for i in comp_string if not i.isdigit()])
It creates a new string using .join from a list. That list is created using a list comprehension that iterates through characters in your original string, and excludes all digits.
This will remove any characters that ARE NOT letters, by going through each character and only adding it to the output if it is a letter:
output_string = ""
for char in Comp_String:
if char.isalpha():
output_string = output_string + char
This will remove any characters that ARE numbers, by going through each character and only adding it to the output if it is not a number:
output_string = ""
for char in Comp_String:
if not char.isdigit():
output_string = output_string + char
You can do it with regular expressions using the https://docs.python.org/3.6/library/re.html module. The only regex you need is \d, which notates digits.
from re import sub
comp_string = "xxf1,aff242342"
print(sub(pattern=r"\d", repl=r"", string=comp_string))

Categories