How continually add to a string? - python

I'm trying to add to a string over a few function calls that you could basically say will "update" the string. So for example, if you had:
'This is a string'
You could change it to:
'This is my string'
Or then:
'This is my string here'
etc..
My data for the string is coming from a nested dictionary, and I made a function that will change it to a string. This function is called 'create_string()'. I won't post it because it is working fine (although if necessary, I'll make an edit. But take my word for it that it's working fine).
Here's the function 'updater()' which takes three arguments: The string, the position you want to change and the string you want to insert.
def updater(c_string, val, position):
data = c_string.split(' ')
data[position] = str(val)
string = ' '.join(data)
return string
x = create_string(....)
new_string = updater(x,'hey', 0)
Which up until this point works fine:
'hey This is a string'
But when you add another function call, it doesn't keep track of the old string:
new_string = updater(x,'hey',0)
new_string = updater(x,'hi',2)
> 'This is hi string'
I know that the reason is likely because of the variable assignment, but i tried just simply calling the functions, and I still had no luck.
How can I get this working?
Thanks for the help!
Note: Please don't waste your time on the create_string() function, it's working fine. It's only the updater() function and maybe even just the function calls that I think are the problem.
**Edit:**Here's what the expected output would look like:
new_string = updater(x,'hey',0)
new_string = updater(x,'hi',2)
> 'hey is hi string'

You need to do this, to keep modifying the string:
new_string = updater(x, 'hey', 0)
new_string = updater(new_string, 'hi', 2)
x is the same after the first call, the new modified string is new_string from that point on.

You store the result of updater to new_string, but don't pass that new_string to the next updater call.

Related

convert word to letter

Code:
mapping = {'hello':'a', 'world':'b'}
string = 'helloworld'
out = ' '.join(mapping.get(s,s) for s in string.split())
print(out)
What I want to happen is that string = 'helloworld'gets printed as ab
What I get as the output is 'helloworld'
The reason is I don't have a space between the string hello and world but I don't want a space in-between them. Can anyone help?
A crude solution in this case would be to simply replace according to the mapping.
def replace(string, mapping):
for k, v in mapping.items():
string = string.replace(k, v)
return string
You get the output helloworld because string.split() from your code returns 'helloworld', which is what you already had to start with. The split does nothing because split, by default, will split a string by a space; of which there are none in your string.
>>>'helloworld'.split()
['helloworld']
If you change the following line, you will get a b as your output.
string = 'hello world'
I am going to assume that you say that you "don't want a space in between them", you mean that you don't want a space between a and b. To achieve that, change the following line:
out = ''.join(mapping.get(s,s) for s in string.split())
This will output ab

Clean long string from spaces and tab in python

supposing to have a long string to create and this string is within a method of a class, what is the best way to write the code?
def printString():
mystring = '''title\n
{{\\usepackage}}\n
text continues {param}
'''.format(param='myParameter')
return mystring
this method is well formatted but the final string has unwanted spaces:
a = printString()
print(a)
title
{\usepackage}
text continues myParameter
while this method gives the corrected results but the code can become messy if the string(s) is long:
def printString():
mystring = '''title\n
{{\\usepackage}}\n
text continues {param}
'''.format(param='myParameter')
return mystring
a = printString()
print(a)
title
{\usepackage}
text continues myParameter
some hints to have a good code quality and the results?
Try enclosing the string you want with brackets, like so:
def printString():
mystring = ('title\n'
'{{\\usepackage}}\n'
'text continues {param}').format(param='myParameter')
return mystring
This would allow you to break the string to several lines while c=having control over the whitespace.
You can use brackets to maintain tidiness of long strings inside functions.
def printString():
mystring = ("title\n"
"{{\\usepackage}}\n"
"text continues {param}"
).format(param='myParameter')
return (mystring)
print(printString())
Results in:
title
{\usepackage}
text continues myParameter
You may also wish to explicitly use the + symbol to represent string concatenation, but that changes this from a compile time operation to a runtime operation. Source
def printString():
mystring = ("title\n" +
"{{\\usepackage}}\n" +
"text continues {param}"
).format(param='myParameter')
return (mystring)
You can use re.sub to cleanup any spaces and tabs at the beginning of each lines
>>> import re
>>> def printString():
... mystring = '''title\n
... {{\\usepackage}}\n
... text continues {param}
... '''.format(param='myParameter')
...
... return re.sub(r'\n[ \t]+', '\n', mystring)
...
This gives the following o/p
>>> a = printString()
>>> print (a)
title
{\usepackage}
text continues myParameter

How to put an argument of a function inside a raw string

I want to create a function that will delete a character in a string of text.
I'll pass the string of text and the character as arguments of the function.
The function works fine but I don't know how to do this correctly if I want to threat it as a raw string.
For example:
import re
def my_function(text, ch):
Regex=re.compile(r'(ch)') # <-- Wrong, obviously this will just search for the 'ch' characters
print(Regex.sub('',r'text')) # <-- Wrong too, same problem as before.
text= 'Hello there'
ch= 'h'
my_function(text, ch)
Any help would be appreciated.
How about changing:
Regex=re.compile(r'(ch)')
print(Regex.sub('',r'text'))
to:
Regex=re.compile(r'({})'.format(ch))
print(Regex.sub('',r'{}'.format(text)))
However, simpler way to achieve this is using str.replace() as:
text= 'Hello there'
ch= 'h'
text = text.replace(ch, '')
# value of text: 'Hello tere'
def my_function(text, ch):
text.replace(ch, "")
This will replace all occurrences of ch with an empty string. No need to invoke the overhead of regular expressions in this.

Replace contents after specific character using template filter in django

I've been trying this for some time now, I want django to replace any "#variable" it finds inside a string with something else.
So for example, if we wanted # to return the number of characters:
'Hello, this is my string. #barbaz knows about it, #foo also knows
about it.'
would turn into
'Hello, this is my string. 6 knows about it, 3 also knows about it.'
This is what I've tried so far:
#register.filter(is_safe=True)
def parse_users(value):
user_count = range(value.count('#'))
for count in user_count:
result = value[value.find('#')+1:value.find(' ')]
print(result)
return string
but this just prints an empty string.
I'd suggest to use regex here.
import re
def parse_users(value):
usernames = re.findall(r"#\w+", value)
for username in usernames:
value = value.replace(username, str(len(username[1:])))
value result: 'Hello, this is my string. 6 knows about it, 3 also knows about it.'
value.find(' ') will return the same thing regardless of '#''s existence in value. You can change it to something like this:
for count in user_count:
from_at = value[value.find('#')+1:]
result = from_at[:from_at.find(' ')]
print(result)

string.upper(<str>) and <str>.upper() won't execute

I have the following bit of code:
def test():
fragment = ''
fragment = raw_input('Enter input')
while fragment not in string.ascii_letters:
fragment = raw_input('Invalid character entered, try again: ')
fragment.upper()
print fragment*3
However when I run it, say for an input value of p, fragment gets printed as 'ppp' - all lower case, i.e. the fragment.upper() line does not run. The same thing happens if I replace that line with string.upper(fragment) (and adding import string at the beginning). Can someone tell me what I'm doing wrong?
Strings are immutable. So functions like str.upper() will not modify str but return a new string.
>>> name = "xyz"
>>> name.upper()
'XYZ'
>>> print name
xyz # Notice that it's still in lower case.
>>> name_upper = name.upper()
>>> print name_upper
XYZ
So instead of fragment.upper() in your code, you need to do new_variable = fragment.upper()and then use this new_variable.
You're not realizing that strings in Python are immutable and that string methods and operations return new strings.
>>> print 'ppp'.upper()
PPP
String is a immutable object, so when you call
string.upper()
python would make a copy of the string, and when you come back call
print string
, it would be the original string, which is lower case. So when you need its upper case version, you have to say:
print string.upper()

Categories