Home > Net >  Concatenating strings in not the correct way
Concatenating strings in not the correct way

Time:02-04

I have created a function that takes 2 input streams from text files, reads them line by line and appends one to the other.

a = open("lib\lists\words.txt")
b = open("lib\lists\extensions.txt")

def iterateLists(word, ext):
    #Crafting the word
    wordLines = word.readlines()
    extLines = ext.readlines()
    for line1 in extLines:
        for line2 in wordLines:
            x = line1
            y = line2
            z = y x
            print(z)

iterateLists(a, b)

However what is happening is the last word in the wordlist is being appended correctly however the rest append the extension below the word (looks like it's taking the newline from the end of the word and appending that to the string, too).

Here is the output:

hello
.php

goodbye
.php

cyah.php

hello
.exe

goodbye
.exe

cyah.exe

hello
.html
goodbye
.html
cyah.html

Process finished with exit code 0

The last word is "cyah" in the wordlist which as you can see is the only one that seems to work. How would I solve this?

CodePudding user response:

You need to remove the new line character with .strip(). Just change these lines:

Instead of:

x = line1
y = line2

Use this:

x = line1.strip()
y = line2.strip()

Full Code:

a = open("lib\lists\words.txt")
b = open("lib\lists\extensions.txt")

def iterateLists(word, ext):
    #Crafting the word
    wordLines = word.readlines()
    extLines = ext.readlines()
    for line1 in extLines:
        for line2 in wordLines:
            x = line1.strip()
            y = line2.strip()
            z = y x
            print(z)

iterateLists(a, b)

CodePudding user response:

You need to remove the break-line character (\n)

So instead of

x = line1
y = line2

you would do

x = line1.replace('\n', '')
y = line2.replace('\n', '')

  •  Tags:  
  • Related