This question already has answers here:
Replacing instances of a character in a string
(17 answers)
Closed 6 years ago.
I want to transform the string 'one two three' into one_two_three.
I've tried "_".join('one two three'), but that gives me o_n_e_ _t_w_o_ _t_h_r_e_e_...
how do I insert the "_" only at spaces between words in a string?
You can use string's replace method:
'one two three'.replace(' ', '_')
# 'one_two_three'
str.join method takes an iterable as an argument and concatenate the strings in the iterable, string by itself is an iterable so you will separate each character by the _ you specified, if you directly call _.join(some string).
You can also split/join:
'_'.join('one two three'.split())
And if you want to use join only , so you can do like thistest="test string".split()
"_".join(test)
This will give you output as "test_string".
Related
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']
This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 2 years ago.
I have two strings:
my_str_1 = '200327_elb_72_ch_1429.csv'
my_str_2 = '200327_elb_10_ch_1429.csv'
When I call .strip() method on both of them I get results like this:
>>> print(my_str_1.strip('200327_elb_'))
'ch_1429.csv'
>>> print(my_str_2.strip('200327_elb_'))
'10_ch_1429.csv'
I expected result of print(my_str_1.strip('200327_elb_')) to be '72_ch_1429.csv'. Why isn't it that case? Why these two result aren't consistent? What am I missing?
From the docs:
[...] The chars argument is a string specifying the set of characters to be removed. [...] The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped [...]
This method removes all specified characters that appear at the left or right end of the original string, till on character is reached that is not specified; it does not just remove leading/trailing substrings, it takes each character individually.
Clarifying example (from Jon Clements comment); note that the characters a from the middle are NOT removed:
>>> 'aa3aa3aa'.strip('a')
'3aa3'
>>> 'a4a3aa3a5a'.strip('a54')
'3aa3'
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.
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]
This question already has answers here:
How to find and replace nth occurrence of word in a sentence using python regular expression?
(9 answers)
Closed 6 years ago.
I'm looking to remove a ',' (comma) from a string, but only the second time the comma occurs as it needs to be in the correct format for reverse geocoding...
As an example I have the following string in python:
43,14,3085
How would I convert it to the following format:
43,143085
I have tried using regex and str.split() but have not achieved result yet..
If you're sure that string only contains two commas and you want to remove the last one you can use rsplit with join:
>>> s = '43,14,3085'
>>> ''.join(s.rsplit(',', 1))
'43,143085'
In above rsplit splits starting from the end number of times given as a second parameter:
>>> parts = s.rsplit(',', 1)
>>> parts
['43,14', '3085']
Then join is used to combine the parts together:
>>> ''.join(parts)
'43,143085'
What about something like:
i = s.find(',')
s[:i] + ',' + s[i+1:].replace(",", "")
This will get rid of all your commas excepts the first one:
string = '43,14,3085'
splited = string.split(',')
string=",".join(splited[0:2])
string+="".join(splited[2:])
print(string)