Insert a string before a substring of a string - python

I want to insert some text before a substring in a string.
For example:
str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"
I want:
str = "thisissomeXXtextthatiwrote"
Assuming substr can only appear once in str, how can I achieve this result? Is there some simple way to do this?

my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"
idx = my_str.index(substr)
my_str = my_str[:idx] + inserttxt + my_str[idx:]
ps: avoid using reserved words (i.e. str in your case) as variable names

Why not use replace?
my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"
my_str.replace(substr, substr + inserttxt)
# 'thisissometextXXthatiwrote'

Use str.split(substr) to split str to ['thisissome', 'thatiwrote'], since you want to insert some text before a substring, so we join them with "XXtext" ((inserttxt+substr)).
so the final solution should be:
>>>(inserttxt+substr).join(str.split(substr))
'thisissomeXXtextthatiwrote'
if you want to append some text after a substring, just replace with:
>>>(substr+appendtxt).join(str.split(substr))
'thisissometextXXthatiwrote'

With respect to the question (were ´my_str´ is the variable), the right is:
(inserttxt+substr).join(**my_str**.split(substr))

Related

Replace string in list using dictionary in Python

How can I replace string in list using dictionary?
I have
text = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}
I want:
correct = ["Hellow
World"]
I have try:
def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
But:
AttributeError: 'list' object has no attribute 'replace'
What you have is mostly correct except your correct function seems to be wanting to correct only a single str (e.g. "h#**o+" => "hellow"), whereas your variable text is currently a list or strs. So if you want to get "hellow world" you need to call correct multiple times to get a list of corrected words, which you can then join into a string.
Try this runnable example!
#!/usr/bin/env python
words = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}
def correct(text,replacement):
for word, replacement in replacement.items():
text = text.replace(word, replacement)
return text
def correct_multiple(words, replacement):
new_words = [correct(word, replacement) for word in words] # get a list of results
combined_str = " ".join(new_words) # join the list into a string
return combined_str
output = correct_multiple(words, replacement)
print(f"{output=}")
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>
You can do this too:
text = ["h#**o+","+&&&orld"]
replacement = {"#":"e","*":"l","+":"w","&":""}
string1 = " ".join(text) # join the words into one string
string2 = string1.translate(string1.maketrans(replacement))
string3 = string2.title()
print(string1 + '\n' + string2 + '\n' + string3)
# h#**o+ +&&&orld
# hellow world
# Hellow World
I've separated the proceedings into 3 successive steps to demonstrate the effect of each step.
text is a LIST of strings, not a string. You can't call string methods on it.
text[0].replace() would be a thing...

Python: Replace character RANGE in a string with new string

Given the following string:
mystring = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
The goal is to swap out a character position range with other characters.
For example, swap out characters 20-24 with ABCDE.
The result would look like:
XXXXXXXXXXXXXXXXXXXABCDEXXXXXXXXXXXXXXX
Testing:
mystring = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
mystring[20:24] = 'ABCDE'
I get the error: TypeError: 'str' object does not support item assignment
The end goal is a reusable function such as:
def replace_chars(some_string, start_char, end_char, replace_string):
if len(replace_string) == (end_char_pos - start_char_pos + 1):
some_string[start_char:end_char] = replace_string
else:
print "replace string invalid length"
sys.exit(1)
return mystring
new_string = replace_chars('XYZXYZ', 2, 4, 'AAA')
I realize that it's possible to pad out the unchanged range into a new string:
mystring = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
mystring = mystring[0:19] + 'ABCDE' + mystring[25:38]
However that will force more calculation and since this will be happening thousands of times against lines in a file. The different lines will be different length and will be different character positions to swap. Doing this seems like it would be a long workaround where I should just be able to insert direct into the character positions in-place.
Appreciate any help, thanks!
strings are immutable (unchangeable). But you can index and join items.
mystring = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
mystring = 'ABCDE'.join([mystring[:20],mystring[24:]])
'XXXXXXXXXXXXXXXXXXXXABCDEXXXXXXXXXXXXXX'
Do be careful as the string length "ABCDE" and the number of items you omit between mystring[:20], mystring[24:] need to be the same length.
Strings are immutable in python! You'll have to split the string into three pieces and concatenate them together :)
mystring = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
new_str = "ABCDE"
first_piece = mystring[0:20]
third_piece = mystring[24:len(mystring)]
final_string = first_piece + new_str + third_piece
This is not strictly possible in python, but consider using bytearray a similar structure to a string in python, with a key difference being mutability
In [52]: my_stuff = bytearray('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
In [53]: my_stuff = my_stuff[0:19] + "abcd" + my_stuff[25:38]
In [54]: print my_stuff
XXXXXXXXXXXXXXXXXXXabcdXXXXXXXXXXXXX
There are some key things you should know when using a bytearray, you can see some of them here
As much as you think you should be able to assign to individual characters of a string, 'str' object does not support item assignment says you can't.

How to extract string in Python

I want to extract specific string from a string, but it shows error. Why can't I use the find as index to extract string ?
Here is my code
string = 'ABP'
p_index = string.find('P')
s = string[0, p_index]
print(s)
TypeError: string indices must be integers
s = string[0, p_index] isn't a valid syntax in python, you should rather do:
s = string[0:p_index]
Since an omitted first index defaults to zero, this returns the same result:
s = string[:p_index]
I'd recommend reading this page for reference on Python string's slicing and it's syntax in general.
You should change this line:
s = string[0, p_index]
with
s = string[p_index]
You don't need to put anything rather than the index of the letter to get 'P' and you found the index with string.find('P') already.
If you mean substracting the 'P' letter from 'ABP' then use:
new_string = 'ABP'.replace('P','')
I'm pretty sure you slice strings like this s = string[0:2]
string = 'ABP'
p_index = string.index('P')
s = string[p_index]
print(s)
string = 'ABP'
p_index = string.find('P')
s = string[p_index]
print(s)
maybe you can try it like this two

Converting regex whitespace characters from list into string

So i want to convert regex whitespaces into a string for example
list1 = ["Hello","\s","my","\s","name","\s","is"]
And I want to convert it to a string like
"Hello my name is"
Can anyone please help.
But also if there was characters such as
"\t"
how would i do this?
list = ["Hello","\s","my","\s","name","\s","is"]
str1 = ''.join(list).replace("\s"," ")
Output :
>>> str1
'Hello my name is'
Update :
If you have something like this list1 = ["Hello","\s","my","\s","name","\t","is"] then you can use multiple replace
>>> str1 = ''.join(list).replace("\s"," ").replace("\t"," ")
>>> str1
'Hello my name is'
or if it's only \t
str1 = ''.join(list).replace("\t","anystring")
I would highly recommend using the join string function mentioned in one of the earlier answers, as it is less verbose. However, if you absolutely needed to use regex in order to complete the task, here's the answer:
import re
list1 = ["Hello","\s","my","\s","name","\s","is"]
list_str = ''.join(list1)
updated_str = re.split('\\\s', list_str)
updated_str = ' '.join(updated_str)
print(updated_str)
Output is:
'Hello my name is'
In order to use raw string notation, replace the 5th line of code with the one below:
updated_str = re.split(r'\\s', list_str)
Both will have the same output result.
You don't even need regular expressions for that:
s = ' '.join([item for item in list if item is not '\s'])
Please note that list is an invalid name for a variable in python as it conflicts with the list function.

how to append a smaller string in between a larger string in python?

I am new to python and i want to append a smaller string to a bigger string at a position defined by me. For example, have a string aaccddee. Now i want to append string bb to it at a position which would make it aabbccddee. How can I do it? Thanks in advance!
String is immutable, you might need to do this:
strA = 'aaccddee'
strB = 'bb'
pos = 2
strC = strA[:pos]+strB+strA[pos:] # get aabbccddee
You can slice strings up as if they were lists, like this:
firststring = "aaccddee"
secondstring = "bb"
combinedstring = firststring[:2] + secondstring + firststring[2:]
print(combinedstring)
There is excellent documentation on the interwebs.
There are various ways to do this, but it's a tiny bit fiddlier than some other languages, as strings in python are immutable. This is quite an easy one to follow
First up, find out where in the string c starts at:
add_at = my_string.find("c")
Then, split the string there, and add your new part in
new_string = my_string[0:add_at] + "bb" + my_string[add_at:]
That takes the string up to the split point, then appends the new snippet, then the remainder of the string
try these in a python shell:
string = "aaccddee"
string_to_append = "bb"
new_string = string[:2] + string_to_append + string[2:]
you can also use a more printf style like this:
string = "aaccddee"
string_to_append = "bb"
new_string = "%s%s%s" % ( string[:2], string_to_append, string[2:] )
Let say your string object is s=aaccddee. The you can do it as:
s = s[:2] + 'bb' + s[2:]

Categories