Output variable value in a string [duplicate] - python

This question already has answers here:
Is there a Python equivalent to Ruby's string interpolation?
(9 answers)
Closed 8 years ago.
In Ruby I can do this:
"This is a string with the value of #{variable} shown."
How do I do that same thing in Python?

You have a lot of options.
"This is a string with the value of " + str(variable) + " shown."
"This is a string with the value of %s shown." % (str(variable))
"This is a string with the value of {0} shown.".format(variable)

The modern/preferred way is to use str.format:
"This is a string with the value of {} shown.".format(variable)
Below is a demonstration:
>>> 'abc{}'.format(123)
'abc123'
>>>
Note that in Python versions before 2.7, you need to explicitly number the format fields:
"This is a string with the value of {0} shown.".format(variable)

this is one of the way we can also do
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')

Related

Trying to find a command so I can get string (e.g. name) out of a bigger string [duplicate]

This question already has answers here:
getting string between 2 characters in python
(4 answers)
Closed 1 year ago.
I've been trying to find a command so I can get the name out of a string formatted like "some string some string <name> some string"
I managed to make a code for this kind of job but if there is a better way, let's say a command for exactly that, I'd be very glad.
Code example:
def findName(str):
indexOne = str.index('<')
indexTwo = str.index('>')
resultList = []
for i in str:
if str.index(i) > indexOne and str.index(i) < indexTwo:
resultList.append(i)
return "".join(resultList)
You can simplify your solution with slicing:
>>> string = "some string some string <name> some string"
>>> string[string.index("<")+1:string.index(">")]
'name'
Or you can use a regex and re.search() for this:
import re
string = "some string some string <name> some string"
match = re.search("<(.*)>", string)
if match:
print("Found:", match.group(1))
else:
print("Not found")
Output
Found: name
If you have a string that is like
a = 'somestring1 somestring2 somestring3 <Stack Overflow> somestring4'
Then you can do something like this:
import re
words = re.findall(r'<(.*)>',a)
print(words)

% symbol and regular expressions [duplicate]

This question already has answers here:
What does % do to strings in Python?
(4 answers)
Closed 3 years ago.
How does this line of code work? Google searches on individual characters don't work well.
re.sub(r'(.*>.*/.*)%s(_R[12].*)' % sample.group(1), r'\1%s\2' % sample_name[1], line)
What I don't understand:
"% sample.group(1)" .... what is % doing?
'\1%s\2' %
%s
What I understand:
re.sub(x,y,z) will substitute x for y in string z
r is for raw (don't mess with /)
arrays & indexes
_R[12].* matches "_R" and a 1 or 2 followed by random characters.
line (it's a string)
Thanks!
The % string operator is used for string interpolation/formatting. Think sprintf or String.format:
r'(.*>.*/.*)%s(_R[12].*)' % sample.group(1)
Equals
r'(.*>.*/.*)' + sample.group(1) + r'(_R[12].*)'
Specifically, the s operator (i.e., %s) is defined as:
String (converts any Python object using str()).
.format is the modern way to go, though.

Why can .format() not be used separately from the declaration? [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 4 years ago.
Can someone explain to me what is going on with the .format() method that it only works off a string declaration and not on a variable containing a string?
Below are the example of the working and failing code followed by the output of each
# This works fine
s = "{0} \n" \
"{1} \n" \
"{2}\n" \
.format("Hello", "world", "from a multiline string")
print(s)
# This does not
f = "{0} \n" \
"{1} \n" \
"{2}\n"
f.format("Hello", "world", "from a multiline string")
print(f)
respective output
Hello
world
from a multiline string
{0}
{1}
{2}
I have tried this with no numbers in braces({}) as well as by assigning names ({aname}) and passing keyword arguments. I'd like to understand the difference between the first and second examples in how the format method processes them, and if there is a way to format a variable containing a string separate from the actual declaration.
It is working, but you will need to reassign it back since it is not in-place (= it creates a new string object, just like any other str method).
f = "{0} \n" \
"{1} \n" \
"{2}\n"
f = f.format("Hello", "world", "from a multiline string")
print(f)
# Hello
# world
# from a multiline string
because .format function returns the formatted string.
It doesn't format the string on which it's called, but it will return you a new string object having the formatted result.

Python Using (%s) in a string that slo contains a (%)? [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 8 years ago.
I have a string that contains a % that I ALSO want to use %s to replace a section of that string with a variable. Something like
name = 'john'
string = 'hello %s! You owe 10%.' % (name)
But when I run it, I get
not enough arguments for format string
I'm pretty sure that means that python thinks I'm trying to insert more than 1 variable into the string but only included the one. How do I overcome this? Thanks!
You can use a % in your string using this syntax, by escaping it with another %:
>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
More about: String Formatting Operations - Python 2.x documentation
As #Burhan added after my post, you can bypass this problem by using the format syntax recommended by Python 3:
>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
In addition to what Maxime posted, you can also do this:
>> name = 'john'
>>> str = 'Hello {}! You owe 10%'.format(name)
>>> str
'Hello john! You owe 10%'

How to put special character between string [duplicate]

This question already has answers here:
How to convert hexadecimal string to bytes in Python?
(7 answers)
Closed 9 years ago.
I have a string like "0013A200305EFF96". I want to change it to be in form "\x00\x13\xA2\x00\x30\x5E\xFF\x96". The special character is "\x". How can I do this in a time efficient way?
Python2
>>> "0013A200305EFF96".decode("hex")
'\x00\x13\xa2\x000^\xff\x96'
Python3
>>> bytes.fromhex("0013A200305EFF96")
b'\x00\x13\xa2\x000^\xff\x96'
gnibbler's answer is probably what you are really looking for; but for completeness, here is how you can insert any sequence:
>>> '\\x'.join(a[i:i+2] for i in xrange(0, len(a), 2))
If you mean literal \x:
import re
s= "0013A200305EFF96"
s=re.sub("(..)", r"\x\1",s)
print s
Output
\x00\x13\xA2\x00\x30\x5E\xFF\x96

Categories

Resources