Current Showreel

Wednesday, 9 September 2015

Python Cheat Sheets - String Concatenation

String Concatenation

Here's some notes I've built up on Python for my own reference.You should be able to copy and paste these into python without too much trouble.If you've found this from a far corner of the 'tinter-webs then leave a comment if any of it doesn't make sense.


### BASICS ###
# set up some variables
xNum = 0
xStr = "MyString"

# basic concatenation of two strings. use a + sign
MyNewVar = xStr + "_IsVeryCool"
print MyNewVar
# python would print "MyString_IsVeryCool"

### MAKE A NUMBER A STRING ###
# will make a number/integer (xNum) into a string. The number 6 becomes the character "6"

str(xNum)

### MAKE A STRING A NUMBER ###
# will make a string into a number (the reverse of above)
int(xStr)



### CONCATENATE MULTIPLE THINGS ###
# to concatenate a string into another string.:
#    1. use %s where you want the string variable to go
#    2. put %[your variable here] after the string
#    use %d to concatenate a number into a string
#    see the examples below

VarText = "sentence"
VarWord =  "words"

# Eg1. -  Basic
VarSentence = "My long %s needs something" %VarText
# python would print "My long sentence needs something"

# Eg.2 - Multiple. Use brackets. Strings will be added in the order you put them in the brackets
VarSentence = "My long %s needs some %s" %(VarText, VarWord)
print VarSentence
# python would print "My long sentence needs some words"

1 comment:

  1. Great article tom, i will recommend every programer should check it out for we have a lot of helpful and informative tips. Thanks for sharing this here.

    ReplyDelete