Removing ' from strings in list [duplicate] - python

This question already has answers here:
Replace part of a string in Python?
(3 answers)
Closed 4 years ago.
I'm trying to remove or ignore the ' symbol (Apostrophe) within a list of strings. I don't know if my for loop is just plain wrong or what:
n = ["a", "a's", "aa's"] #example list
for i in n:
i.strip("'")

strip won't work here use replace,
In [9]: [i.replace("'",'') for i in lst]
Out[9]: ['a', 'as', 'aas']

Two problems here.
First, strip doesn't work in the middle of the string, you have to use `replace("'", "")
Second, and more important, strings are immutable. Even if i.strip(...) did what you want, it would not change i. It would just produce a new string. So, you have to store that string.
Sum up, try something like
n = [i.replace("'", "") for i in n]

Related

Removing a character (number, letter, anything) in a string that is the same as the one that came before or after? (Python) [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 months ago.
So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.
This is probably a lot more simple than what I'm doing, but this is what I've been attempting to do (and failing miserably at)
for j in range(2, len(string)-1):
char = string[j]
plus = string[j+1]
minus = string[j-1]
if char == plus or char == minus:
string.replace(char, "")
For reference, the code SHOULD act as:
input: ppmpvvpmmp
output: pmpvmp
But instead, the output does not change at all.
Again, I'm aware that this is most likely very easy and I'm overcomplicating, but I'm genuinely struggling here and have tried a lot of similar variations
I would use a regular expression replacement here:
inp = "ppmpvvpmmp"
output = re.sub(r'(\w)\1', r'\1', inp)
print(output) # pmpvpmp
The above assumes that a duplicate is limited to a single pair of same letters. If instead you want to reduce 3 or more, then use:
inp = "ppmpvvvvvpmmmp"
output = re.sub(r'(\w)\1+', r'\1', inp)
print(output) # pmpvpmp

Split string into list by separate delimiters, but only by certain instances of said delimiters [duplicate]

This question already has answers here:
Split string with multiple delimiters in Python [duplicate]
(5 answers)
Closed 2 years ago.
I think what I'm trying to achieve is fairly common but I can't find reference for it on the internet; either that or I'm misphrasing what I'm trying to do.
This is the string I would like to split:
array_1:target:radec, 0:00:00.00, -90:00:00.0
I would like to split it by the first two colons (':'), and by the first comma & space (', '), such that I get
['array_1', 'target', 'radec', '0:00:00.00, -90:00:00.0']
I've tried to run split() with arguments twice on the original string, and it fails on the second split() because I'm trying to split something that's already a list. All the other answers I can find seem to focus on splitting the string by all instances of a delimiter, but I want the last field in the list 0:00:00.00, -90:00:00.0 to remain like it is.
First split it by the first ", " (using maxsplit=1), then the first element of the resulting list split by ":":
s = "array_1:target:radec, 0:00:00.00, -90:00:00.0"
temp = s.split(", ", maxsplit=1)
temp[0] = temp[0].split(":")
result = temp[0] + [temp[1]]
The result:
['array_1', 'target', 'radec', '0:00:00.00, -90:00:00.0']
How about
l1 = s.split()
l2 = l1[0].split(':') + l1[1:]
This will first split by whitespace separator, then split the first element (only) by a colon separator, and then join the lists. Result:
['array_1', 'target', 'radec,', '0:00:00.00,', '-90:00:00.0']

How to get the numbers from a string (contains no spaces between letters and numbers)? [duplicate]

This question already has answers here:
How to extract numbers from a string in Python?
(19 answers)
Closed 3 years ago.
So, I have a string "AB256+74POL". I want to extract the numbers only into a list say num = [256,74]. How to do this in python?
I have tried string.split('+') and followed by iterating over the two parts and adding the characters which satisfy isdigit(). But is there an easier way to that?
import re
a = 'AB256+74POL'
array = re.findall(r'[0-9]+', a)
"".join([c if c.isdigit() else " " for c in mystring]).split()
Explanation
Strings are iterable in python. So we iterate on each character in the string, and replace non digits with spaces, then split the result to get all sequences of digits in a list.

adding string ending "\" to all elements of a list of strings [duplicate]

This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 6 years ago.
I have a list of strings: ['John','William','Ken','Rogers']. I need to prepend "Corp\" to each element in the list so that the final list looks like this:
['Corp\John','Corp\William','Corp\Ken','Corp\Rogers']
I tried the following:
s=['John','William','Ken','Rogers']
users=['Corp\\' + m for m in s]
print(users)
The output gives me
['Corp\\John','Corp\\William','Corp\\Ken','Corp\\Rogers']
If I try users=['Corp\' + m for m in s] I get an obvious error:
"StringError EOL while scanning string literal"
I would need each element in the exact form 'Corp\name', as this needs to be used in a for loop to validate users who are eligible to login.
This may be a problem with how you're 'outputting' the list. Using the REPL:
>>> lsa = ["Corp\{}".format(item) for item in ls]
>>> print(lsa)
['Corp\\Jenna', 'Corp\\Wilma', 'Corp\\Katie', 'Corp\\Rebecca']
>>> for i in lsa:
... print(i)
...
Corp\Jenna
Corp\Wilma
Corp\Katie
Corp\Rebecca
As you can see, in the first print, that prints the full list, we see two slashes. This is because Python is saying that the second slash is escaped. In the second print, inside a for loop, we see that there is only one slash, because we are printing each item individually and the escape string is applied, yielding only a single slash.

Finding all the indexes of a substring given a string containing it in Python [duplicate]

This question already has answers here:
How to get the position of a character in Python?
(11 answers)
Closed 7 years ago.
For example:
my_string = "hi how are you?/nIs everything ok?/nAre you happy?"
I need to make a list containing all the indexes of the newline - (/n).
How can i do it ?
You can use enumerate in a list comprehension to create a list of indices.
>>> [index for index, value in enumerate(my_string) if value == '\n']
[15, 33]
By the way, a new line character is '\n' not '/n' (note the slash)
import re
my_string = "hi how are you?/nIs everything ok?/nAre you happy?"
list = [m.start() for m in re.finditer('/n', my_string)]

Categories

Resources