inserting characters at the start and end of a string - python

I am new and trying to find a way to insert a number of L's at the beginning and end of a string. So if I have a string which says
"where did I put my cupcake this morning"
And I want to insert 1 L at the start and 2 L's at the end, so it looks like: "Lwhere did I put my cupcake this morningLL" How do I do this. thank you

Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:
yourstring = "L" + yourstring + "LL"
Note that you can also create a string with n Ls by using multiplication:
m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)

For completeness along with the other answers:
yourstring = "L%sLL" % yourstring
Or, more forward compatible with Python 3.x:
yourstring = "L{0}LL".format(yourstring)

You can also use join:
yourstring = ''.join(('L','yourstring','LL'))
Result:
>>> yourstring
'LyourstringLL'

If you want to insert other string somewhere else in existing string, you may use selection method below.
Calling character on second position:
>>> s = "0123456789"
>>> s[2]
'2'
Calling range with start and end position:
>>> s[4:6]
'45'
Calling part of a string before that position:
>>> s[:6]
'012345'
Calling part of a string after that position:
>>> s[4:]
'456789'
Inserting your string in 5th position.
>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'
Also s is equivalent to s[:].
With your question you can use all your string, i.e.
>>> s = "L" + s + "LL"
or if "L" is a some other string (for example I call it as l), then you may use that code:
>>> s = l + s + (l * 2)

Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:
s = "something about cupcakes"
print(f"L{s}LL")

Let's say we have a string called yourstring:
for x in range(0, [howmanytimes you want it at the beginning]):
yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
yourstring += "L"

you can use f strings for this
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}'
print(foobar)
you can replace 10 by how many times you want to put L's in your string
for end also you can do the same
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}{bar*10}'
print(foobar)

Related

Append to string up to given value [duplicate]

I should define a function pad_with_n_chars(s, n, c) that takes a
string 's', an integer 'n', and a character 'c' and returns
a string consisting of 's' padded with 'c' to create a
string with a centered 's' of length 'n'. For example,
pad_with_n_chars(”dog”, 5, ”x”) should return the
string "xdogx".
With Python2.6 or better, there's no need to define your own function; the string format method can do all this for you:
In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'
Using f-string: f'{"dog":x^5}'
yeah just use ljust or rjust to left-justify (pad right) and right-justify (pad left) with any given character.
For example ... to make '111' a 5 digit string padded with 'x'es
In Python3.6:
>>> '111'.ljust(5, 'x')
111xx
>>> '111'.rjust(5, 'x')
xx111
It looks like you're only looking for pointers, not a complete solution. So here's one:
You can multiply strings in python:
>>> "A" * 4
'AAAA'
Additionally I would use better names, instead of s I'd use text, which is much clearer. Even if your current professor (I suppose you're learning Python in university.) uses such horrible abbreviations.
In Python 3.x there are string methods: ljust, rjust and center.
I created a function:
def header(txt: str, width=45, filler='-', align='c'):
assert align in 'lcr'
return {'l': txt.ljust, 'c': txt.center, 'r': txt.rjust}[align](width, filler)
print(header("Hello World"))
print(header("Hello World", align='l'))
print(header("Hello World", align='r'))
Output:
-----------------Hello World-----------------
Hello World----------------------------------
----------------------------------Hello World
well, since this is a homework question, you probably won't understand what's going on if you use the "batteries" that are included.
def pad_with_n_chars(s, n, c):
r=n - len(s)
if r%2==0:
pad=r/2*c
return pad + s + pad
else:
print "what to do if odd ? "
#return 1
print pad_with_n_chars("doggy",9,"y")
Alternatively, when you are not schooling anymore.
>>> "dog".center(5,"x")
'xdogx'
print '=' * 60
header = lambda x: '%s%s%s' % ('=' * (abs(int(len(x)) - 60) / 2 ),x,'=' * (abs(int(len(x)) - 60) / 2 ) )
print header("Bayors")

how to add a dot before each letter in a string in python

we get a string from user and want to lowercase it and remove vowels and add a '.' before each letter of it. for example we get 'aBAcAba' and change it to '.b.c.b' . two early things are done but i want some help with third one.
str = input()
str=str.lower()
for i in range(0,len(str)):
str=str.replace('a','')
str=str.replace('e','')
str=str.replace('o','')
str=str.replace('i','')
str=str.replace('u','')
print(str)
for j in range(0,len(str)):
str=str.replace(str[j],('.'+str[j]))
print(str)
A few things:
You should avoid the variable name str because this is used by a builtin, so I've changed it to st
In the first part, no loop is necessary; replace will replace all occurrences of a substring
For the last part, it is probably easiest to loop through the string and build up a new string. Limiting this answer to basic syntax, a simple for loop will work.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
Another potential improvement: for the second part, you can also write a loop (instead of your five separate replace lines):
for c in 'aeiou':
st = st.replace(c, '')
Other possibilities using more advanced techniques:
For the second part, a regular expression could be used:
st = re.sub('[aeiou]', '', st)
For the third part, a generator expression could be used:
st_new = ''.join(f'.{c}' for c in st)
You can use str.join() to place some character in between all the existing characters, and then you can use string concatenation to place it again at the end:
# st = 'bcb'
st = '.' + '.'.join(st)
# '.b.c.b'
As a sidenote, please don't use str as a variable name. It's the name of the "string" datatype, and if you make a variable named it then you can't properly work with other strings any more. string, st, s, etc. are fine, as they're not the reserved keyword str.
z = "aBAcAba"
z = z.lower()
newstring = ''
for i in z:
if not i in 'aeiou':
newstring+='.'
newstring+=i
print(newstring)
Here I have gone step by step, first converting the string to lowercase, then checking if the word is not vowel, then add a dot to our final string then add the word to our final string.
You could try splitting the string into an array and then build a new string with the indexes of the array appending an "."
not too efficient but will work.
thanks to all of you especially allani. the bellow code worked.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
This does everything.
import re
data = 'KujhKyjiubBMNBHJGJhbvgqsauijuetystareFGcvb'
matches = re.compile('[^aeiou]', re.I).finditer(data)
final = f".{'.'.join([m.group().lower() for m in matches])}"
print(final)
#.k.j.h.k.y.j.b.b.m.n.b.h.j.g.j.h.b.v.g.q.s.j.t.y.s.t.r.f.g.c.v.b
s = input()
s = s.lower()
for i in s:
for x in ['a','e','i','o','u']:
if i == x:
s = s.replace(i,'')
new_s = ''
for i in s:
new_s += '.'+ i
print(new_s)
def add_dots(n):
return ".".join(n)
print(add_dots("test"))
def remove_dots(a):
return a.replace(".", "")
print(remove_dots("t.e.s.t"))

Pipe replacement with character

I have this code :
> list=str(raw_input('Enter pipe seprated list [PRIMARY|SECONDARY]:'))
> n_list="^"+list+"$"
> print n_list
when I execute it, it prompts me as :
Enter pipe separated list [PRIMARY|SECONDARY]:PRIMARY
as above if I give PRIMARY its gives me result as :
^PRIMARY$
and if provide the input as PRIMARY|SECONDARY:
Enter pipe seprated list [PRIMARY|SECONDARY]:PRIMARY|SECONDARY
I am getting the output as :
^PRIMARY|SECONDARY$
here I want to get the output as :
^PRIMARY$|^SECONDARY$ if I give the input PRIMARY|SECONDARY. Please help me to achieve this.
Do splitting according to |, add ^ and $ at the start and end of each item. And then join them using |.
>>> s = 'PRIMARY|SECONDARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$|^SECONDARY$
>>> s = 'PRIMARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$
>>> s = 'PRIMARY|SECONDARY|TERTIARY'
>>> print '|'.join(['^' + i + '$' for i in s.split('|')])
^PRIMARY$|^SECONDARY$|^TERTIARY$
>>>
You have to split your string with | (pipe) and concate it with your prefix(^) and postfix($)
l=str(raw_input('Enter pipe seprated list [PRIMARY|SECONDARY]:'))
n_l = "|".join(["^" + l_t + "$" for l_t in l.split('|')])
print n_l
Just for completeness, as an alternative to the split/join solution already proposed, you could also just replace the | with $|^:
>>> s = 'PRIMARY|SECONDARY'
>>> '^' + s.replace('|', '$|^') + '$'
'^PRIMARY$|^SECONDARY$'
However, since in this solution you have to write both ^ and $ twice, I would still prefer the split/join way.
Another solution: Instead of using the regex '^PRIMARY$|^SECONDARY$', you could also use '^(PRIMARY|SECONDARY)$'. The behaviour should be the same.

How do I reverse words in a string with Python

I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:
S = " what is my name"
def reversStr(S):
for x in range(len(S)):
return S[::-1]
break
What I get now is: eman ym si tahw
However, I am trying to get: tahw is ym eman (individual words reversed)
def reverseStr(s):
return ' '.join([x[::-1] for x in s.split(' ')])
orig = "what is my name"
reverse = ""
for word in orig.split():
reverse = "{} {}".format(reverse, word[::-1])
print(reverse)
Since everyone else's covered the case where the punctuation moves, I'll cover the one where you don't want the punctuation to move.
import re
def reverse_words(sentence):
return re.sub(r'[a-zA-Z]+', lambda x : x.group()[::-1], sentence)
Breaking this down.
re is python's regex module, and re.sub is the function in that module that handles substitutions. It has three required parameters.
The first is the regex you're matching by. In this case, I'm using r'\w+'. The r denotes a raw string, [a-zA-Z] matches all letters, and + means "at least one".
The second is either a string to substitute in, or a function that takes in a re.MatchObject and outputs a string. I'm using a lambda (or nameless) function that simply outputs the matched string, reversed.
The third is the string you want to do a find in a replace in.
So "What is my name?" -> "tahW si ym eman?"
Addendum:
I considered a regex of r'\w+' initially, because better unicode support (if the right flags are given), but \w also includes numbers and underscores. Matching - might also be desired behavior: the regexes would be r'[a-zA-Z-]+' (note trailing hyphen) and r'[\w-]+' but then you'd probably want to not match double-dashes (ie --) so more regex modifications might be needed.
The built-in reversed outputs a reversed object, which you have to cast back to string, so I generally prefer the [::-1] option.
inplace refers to modifying the object without creating a copy. Yes, like many of us has already pointed out that python strings are immutable. So technically we cannot reverse a python string datatype object inplace. However, if you use a mutable datatype, say bytearray for storing the string characters, you can actually reverse it inplace
#slicing creates copy; implies not-inplace reversing
def rev(x):
return x[-1::-1]
# inplace reversing, if input is bytearray datatype
def rev_inplace(x: bytearray):
i = 0; j = len(x)-1
while i<j:
t = x[i]
x[i] = x[j]
x[j] = t
i += 1; j -= 1
return x
Input:
x = bytearray(b'some string to reverse')
rev_inplace(x)
Output:
bytearray(b'esrever ot gnirts emose')
Try splitting each word in the string into a list (see: https://docs.python.org/2/library/stdtypes.html#str.split).
Example:
>>string = "This will be split up"
>>string_list = string.split(" ")
>>string_list
>>['This', 'will', 'be', 'split', 'up']
Then iterate through the list and reverse each constituent list item (i.e. word) which you have working already.
def reverse_in_place(phrase):
res = []
phrase = phrase.split(" ")
for word in phrase:
word = word[::-1]
res.append(word)
res = " ".join(res)
return res
[thread has been closed, but IMO, not well answered]
the python string.lib doesn't include an in place str.reverse() method.
So use the built in reversed() function call to accomplish the same thing.
>>> S = " what is my name"
>>> ("").join(reversed(S))
'eman ym si tahw'
There is no obvious way of reversing a string "truly" in-place with Python. However, you can do something like:
def reverse_string_inplace(string):
w = len(string)-1
p = w
while True:
q = string[p]
string = ' ' + string + q
w -= 1
if w < 0:
break
return string[(p+1)*2:]
Hope this makes sense.
In Python, strings are immutable. This means you cannot change the string once you have created it. So in-place reverse is not possible.
There are many ways to reverse the string in python, but memory allocation is required for that reversed string.
print(' '.join(word[::-1] for word in string))
s1 = input("Enter a string with multiple words:")
print(f'Original:{s1}')
print(f'Reverse is:{s1[::-1]}')
each_word_new_list = []
s1_split = s1.split()
for i in range(0,len(s1_split)):
each_word_new_list.append(s1_split[i][::-1])
print(f'New Reverse as List:{each_word_new_list}')
each_word_new_string=' '.join(each_word_new_list)
print(f'New Reverse as String:{each_word_new_string}')
If the sentence contains multiple spaces then usage of split() function will cause trouble because you won't know then how many spaces you need to rejoin after you reverse each word in the sentence. Below snippet might help:
# Sentence having multiple spaces
given_str = "I know this country runs by mafia "
tmp = ""
tmp_list = []
for i in given_str:
if i != ' ':
tmp = tmp + i
else:
if tmp == "":
tmp_list.append(i)
else:
tmp_list.append(tmp)
tmp_list.append(i)
tmp = ""
print(tmp_list)
rev_list = []
for x in tmp_list:
rev = x[::-1]
rev_list.append(rev)
print(rev_list)
print(''.join(rev_list))
output:
def rev(a):
if a == "":
return ""
else:
z = rev(a[1:]) + a[0]
return z
Reverse string --> gnirts esreveR
def rev(k):
y = rev(k).split()
for i in range(len(y)-1,-1,-1):
print y[i],
-->esreveR gnirts

looking to parse a string in python

If I have a series of python strings that I'm working with that will always take the form of
initialword_content
and I want to strip out the initialword portion, which will always be the same number of characters, and then I want to turn all instances of _ into spaces -- since content may have some underscores in it -- what's the easiest way to do that?
strs = "initialword_content"
strs = strs[12:].replace("_", " ")
print strs
Due to the initialword always has same number of character, so you can just get the suffix of the string. And use string.replace to replace all "_" into spaces.
First, split the string once (with the parameter 1 to split) to get two parts: the throw-away 'initialword' and the rest, where you replace all underscores with spaces.
s = 'initialword_content'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content'
s = 'initialword_content_with_more_words'
a, b = s.split('_', 1)
b = b.replace('_', ' ')
# b == 'content with more words'
This can be done with a single command:
s.split('_', 1)[1].replace('_', ' ')
another way:
' '.join(s.split('_')[1:])
or, if the length of "initialword" is always the same (and you don't have to calculate it each time), take the #JunHu's solution.
I used slicing and the replace() function. replace() simply... replaces!
string = 'initialword_content'
content = string[12:] # You mentioned that intialword will always be the same length, so I used slicing.
content = content.replace('_', ' ')
For example:
>>> string = 'elephantone_con_ten_t' # elephantone was the first thing I thought of xD
>>> content = string[12:]
>>> content
... con_ten_t
>>> content = content.replace('_', ' ')
>>> content
... con ten t
However, if you also want to reference "elephantone" somewhere else, do this:
>>> string = 'elephantone_con_ten_t'
>>> l = string.split('_', 1) # This will only strip the string ONCE from the left.
>>> l[0]
... 'elephantone'
>>> l[1].replace('_', ' ')
... 'con ten t'

Categories