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'
Related
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)
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.
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'
>>>
This question already has answers here:
Split a string by spaces -- preserving quoted substrings -- in Python
(16 answers)
Closed 9 years ago.
I have my data as below
string = ' streptococcus 7120 "File being analysed" rd873 '
I tried to split the line using n=string.split() which gives the below result:
[streptococcus,7120,File,being,analysed,rd873]
I would like to split the string ignoring white spaces in " "
# output expected :
[streptococcus,7120,File being analysed,rd873]
Use re.findall with a suitable regex. I'm not sure what your error cases look like (what if there are an odd number of quotes?), but:
filter(None, it.chain(*re.findall(r'"([^"]*?)"|(\S+)', ' streptococcus 7120 "File being analysed" rd873 "hello!" hi')))
> ['streptococcus',
'7120',
'File being analysed',
'rd873',
'hello!',
'hi']
looks right.
You want shlex.split, which gives you the behavior you want with the quotes.
import shlex
string = ' streptococcus 7120 "File being analysed" rd873 '
items = shlex.split(string)
This won't strip extra spaces embedded in the strings, but you can do that with a list comprehension:
items = [" ".join(x.split()) for x in shlex.split(string)]
Look, ma, no regex!
This question already has answers here:
Is there a simple way to remove multiple spaces in a string?
(27 answers)
Closed 6 years ago.
I wanna know how to remove unwanted space in between a string. For example:
>>> a = "Hello world"
and i want to print it removing the extra middle spaces.
Hello world
This will work:
" ".join(a.split())
Without any arguments, a.split() will automatically split on whitespace and discard duplicates, the " ".join() joins the resulting list into one string.
Regular expressions also work
>>> import re
>>> re.sub(r'\s+', ' ', 'Hello World')
'Hello World'