Python Strings and Integer Concatenation

Python strings and integer concatenation

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use:

string = 'string'
for i in range(11):
string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as YOU suggested:

>>> string = "string"
>>> [string+`i` for i in range(11)]


For Python 3

You can use:

string = 'string'
for i in range(11):
string += str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10, you can use this as YOU suggested:

>>> string = "string"
>>> [string+str(i) for i in range(11)]

How can I concatenate a string and a number in Python?

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9
"asd" + str(9)

How can I concatenate str and int objects?

The problem here is that the + operator has (at least) two different meanings in Python: for numeric types, it means "add the numbers together":

>>> 1 + 2
3
>>> 3.4 + 5.6
9.0

... and for sequence types, it means "concatenate the sequences":

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'abc' + 'def'
'abcdef'

As a rule, Python doesn't implicitly convert objects from one type to another1 in order to make operations "make sense", because that would be confusing: for instance, you might think that '3' + 5 should mean '35', but someone else might think it should mean 8 or even '8'.

Similarly, Python won't let you concatenate two different types of sequence:

>>> [7, 8, 9] + 'ghi'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

Because of this, you need to do the conversion explicitly, whether what you want is concatenation or addition:

>>> 'Total: ' + str(123)
'Total: 123'
>>> int('456') + 789
1245

However, there is a better way. Depending on which version of Python you use, there are three different kinds of string formatting available2, which not only allow you to avoid multiple + operations:

>>> things = 5
>>> 'You have %d things.' % things  # % interpolation
'You have 5 things.'
>>> 'You have {} things.'.format(things)  # str.format()
'You have 5 things.'
>>> f'You have {things} things.'  # f-string (since Python 3.6)
'You have 5 things.'

... but also allow you to control how values are displayed:

>>> value = 5
>>> sq_root = value ** 0.5
>>> sq_root
2.23606797749979
>>> 'The square root of %d is %.2f (roughly).' % (value, sq_root)
'The square root of 5 is 2.24 (roughly).'
>>> 'The square root of {v} is {sr:.2f} (roughly).'.format(v=value, sr=sq_root)
'The square root of 5 is 2.24 (roughly).'
>>> f'The square root of {value} is {sq_root:.2f} (roughly).'
'The square root of 5 is 2.24 (roughly).'

Whether you use % interpolation, str.format(), or f-strings is up to you: % interpolation has been around the longest (and is familiar to people with a background in C), str.format() is often more powerful, and f-strings are more powerful still (but available only in Python 3.6 and later).

Another alternative is to use the fact that if you give print multiple positional arguments, it will join their string representations together using the sep keyword argument (which defaults to ' '):

>>> things = 5
>>> print('you have', things, 'things.')
you have 5 things.
>>> print('you have', things, 'things.', sep=' ... ')
you have ... 5 ... things.

... but that's usually not as flexible as using Python's built-in string formatting abilities.


1 Although it makes an exception for numeric types, where most people would agree on the 'right' thing to do:

>>> 1 + 2.3
3.3
>>> 4.5 + (5.6+7j)
(10.1+7j)

2 Actually four, but template strings are rarely used, and are somewhat awkward.


Other Resources:

  • Real Python: Splitting, Concatenating, and Joining Strings in Python
  • Python.org: string - Common string operations
  • python string concatenation with int site:stackoverflow.com

Concatenate string and int in Python 3 .4

Note that print is a function in Python 3. In Python 2, your first line would concatenate "Type string: " and "123" and then print them. In Python 3, you are calling the print function with one argument, which returns None, and then add "123" to it. That doesn't make any sense.

The second line doesn't generate an error in Python 2 or 3 (I've tested it with 2.7.7 and 3.2.3). In Python 2, you get

Concatenate strings and ints 10

while in Python 3, your script should only print

Concatenate strings and ints

This is because again, print is a function, and therefore you call it with the argument "Concatenate strings and ints". The , 10 makes your line a tuple of the return value of print, which is None, and 10. Since you don't use that tuple for anything, there is no visible effect.

Concatenating string and integer in Python

Modern string formatting:

"{} and {}".format("string", 1)

Concatenate strings and integers in a list based on conditions

You were close. instead of checking for equality with type, use 'is'. You can also do isinstance() as pointed out in the comments to check for inheritance and subclasses of str/int.

sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
newlist = []

for s in sample_list:
if type(s) is int:
newlist.append(s + 100)
elif type(s) is str:
newlist.append(s + ' is the name')
else:
newlist.append(s)

newlist2 = []

for s in sample_list:
if isinstance(s, int):
newlist2.append(s + 100)
elif isinstance(s, str):
newlist2.append(s + ' is the name')
else:
newlist2.append(s)

print(newlist)
print(newlist2)

Can't concatenate string with integer

You can only concatenate a string with another string in Python.

Change the last two lines to below:

wList.append(num + num2 + str(salt))
wList.append(num2 + num + str(salt))


Related Topics



Leave a reply



Submit